這對於一個節點/快速/ MongoDB的應用程序,用AJAX調用Node.js EventLoop操作未完成?
出於某種原因,一個
selector.html(
)事件被替換 選擇的HTML,但現在還不是。
唯一的變化是引入在後端的editAll()
功能,它傳遞.get
MongoDB的數據,阿賈克斯將其傳送到前端之前做一些計算。
取而代之的是瀏覽器的控制檯,每個btn.click
[13:47:57.240] GET http://localhost:9999/ [HTTP/1.1 200 OK 5ms]
[13:47:57.174] "Getting All Actions"
[13:47:57.192] "value of action with index 0 = 4"
[13:47:57.193] "value of action with index 1 = 8"
[13:47:57.193] "value of action with index 2 = 9"
[13:48:03.704] GET http://localhost:9999/ [HTTP/1.1 200 OK 7ms]
[13:48:03.640] "Getting All Actions"
[13:48:03.661] "value of action with index 0 = 4"
[13:48:03.661] "value of action with index 1 = 8"
[13:48:03.661] "value of action with index 2 = 9"
..the控制檯寫
GET http://localhost:9999/
的寫了一個全套的「迴應」,一組重複的div出現在前端
[13:29:24.244] GET http://localhost:9999/ [HTTP/1.1 200 OK 5ms]
[13:29:24.182] "Getting All Actions"
[13:29:24.197] "value of doc with index 0 = 24"
[13:29:24.197] "value of doc with index 1 = 28"
[13:29:24.197] "value of doc with index 2 = 29"
...
[13:29:24.198] "value of doc with index 6 = 24"
[13:29:24.198] "value of doc with index 7 = 28"
[13:29:24.199] "value of doc with index 8 = 29"
據我所知,後端工作正常,因爲唯一的3 docs in the db
傳遞給eventAll()函數,該函數再次提供相同的3 docs
。
function getAll(res) {
db.collection('demo').find().sort({ value: 1 }).toArray(function (err, docs) {
console.log("Got the docs: " + utils.inspect(docs));
//res.json({docs: docs}); THIS WORKS PERFECTLY,
but the eventAll() pass causes this frontend issue
/* pass and rebuild the data array before we 'json' it */
var editedDocs = editAll(docs);
res.json({docs: editedDocs});
});
}
一個名爲傳遞數據的editAll()函數,是事件循環操作沒有不散的東西?
function editAll(allDocs) {
var returnedValue = [];
for (var i=0, len=allDocs.length; i < len; ++i){
//does some calculations
var newVal = {_id:allDocs[i]._id,title:allDocs[i].title,value:allDocs[i].value};
returnedValue.push(newVal);
}
console.log(returnedValue);
return (returnedValue);
}
爲什麼每一個btn.click
是要添加另一組的div來#result
這裏的AJAX不用彷徨調用基礎上btn.click一些HTML,通過gotAllSuccess
$('#getBtn').click(function() {
console.log('Getting All');
$.get('http://localhost:9999').
done(gotAllSuccess).
fail(gotAllFailure);
});
function gotAllSuccess(result){
var docs = result.docs;
var html = '';
var doc;
for (var i=0, len=docs.length; i < len; i++){
doc = docs[i];
console.log("value of doc with index " + i + " = " + doc.value);
html += "<div class='rResult' id='rResult" + i + "'>"+doc.title+"</div><br>";
}
$('#result').html(html);
}
首先,你應該檢查你以後'得到的文檔數量editDocs'調用。 你能改說你的問題嗎?它幾乎不可讀。第一眼看不到你的代碼有問題。 –
@Mr_Mig現在正在檢查,並且會在之後重新修改問題。感謝評論 – StackThis
@Mr_Mig更新了問題,它是否更清晰?在editAll()調用之前和之後只有3個文檔存在,但是它們在前端打印了over-and-over,on.btn.click! – StackThis