0
我現在能夠接收數據,因爲蒙戈是恢復對我的許諾MongoDB的,快速 - 不能等待的承諾,承諾{} <pending>
這是我的數據
{ "_id" : ObjectId("59490a250f86a4b4e0cb75b2"), "title" : "a", "array" : [ { "_id" : ObjectId("59490a250f86a4b4e0cb75b3") } ] }
{ "_id" : ObjectId("59490a250f86a4b4e0cb75b3"), "title" : "b", "array" : [ { "_id" : ObjectId("59490a250f86a4b4e0cb75b4") } ] }
{ "_id" : ObjectId("59490a250f86a4b4e0cb75b4"), "title" : "c", "array" : [ { "_id" : ObjectId("59490a250f86a4b4e0cb75b5") }, { "_id" : ObjectId("59490a250f86a4b4e0cb75b6") } ] }
{ "_id" : ObjectId("59490a250f86a4b4e0cb75b5"), "title" : "d" }
{ "_id" : ObjectId("59490a250f86a4b4e0cb75b6"), "title" : "e", "array" : [ { "_id" : ObjectId("59490a250f86a4b4e0cb75b7") } ] }
{ "_id" : ObjectId("59490a250f86a4b4e0cb75b7"), "title" : "f" }
這是我的MongoDB的查詢在蒙戈殼牌
function insertNodes(document) {
var array = document.array;
if (array) {
array.forEach((innerDoc) => {
let foreignKey = {_id: innerDoc._id};
let foreignNode = db.test3.findOne(foreignKey);
array[array.indexOf(innerDoc)] = insertNodes(foreignNode);
});
}
return document;
}
var documents = db.test3.find();
documents.forEach((document) => {
document = insertNodes(document);
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
printjson(document);
});
,但現在我想這樣做的serwer此查詢(因爲我希望收到來自DB數據)
所以我重構這個在控制器
function insertNodes(document) {
var array = document.array;
if (array) {
array.forEach((innerDoc) => {
var foreignKey = {_id: innerDoc._id};
var foreignNode = db.collection('test3').findOne(foreignKey);
foreignNode.then(function (data) {
console.log(data);
foreignNode = data;
});
console.log(foreignNode);
array[array.indexOf(innerDoc)] = insertNodes(foreignNode);
});
}
return document;
}
var documents = db.collection('test3').find();
var docs = [];
documents.forEach((document) => {
docs.push(insertNodes(document));
});
res.send(docs);
,但此行
var foreignNode = db.collection('test3').findOne(foreignKey);
是returnning我
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
後,我添加 「於是」 答應我仍然收到承諾,但我無法做任何事情。
的可能的複製[如何從異步調用返回響應?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-respo異步調用) – 4castle
@ 4castle我不認爲這是相同的,因爲我使用「然後」 –
我鏈接到您正在遇到的問題的規範重複,但第一個答案鏈接到[這個問題](https://stackoverflow.com/q/23667086/5743988),它顯示了你對'then'的使用如何產生與不使用promise相同的結果。 – 4castle