我在 nodejs 檔案中有以下部分
client.db('metro4').collection('Station').findOne({"Name": variabled2}, function(err, res2) {
if(err) throw err;
variabled2 = res2._id;
console.log("id2 = ", res2._id);
});
console.log("v= ",variabled2);
myFunc(variabled);
該myFunc函式還有一些 mongodb 查詢。
問題在于執行順序。
v = undefined
then some of function results (which are obviously wrong)
id2 = 4
then other of functions results
我來自在節點內運行 MySQL 查詢,即使在長存盤程序中也沒有這些問題。
現在很多答案都建議“異步和等待”。所以,我做了myFunc async并嘗試了這個
(async function() {
await recur2();
})();
但正如預期的那樣,結果幾乎與程式不等待第一次查詢相同。
另外,我發現.then()像Promises我在上面的查詢中那樣具有回呼函式時它們顯然不起作用。
提前致謝。
uj5u.com熱心網友回復:
第一個查詢使用回呼,因此它不會等待完成。所以你需要的是await第一個查詢,或者myFunc放入回呼中。
放在回呼里面
let variabled2;
client.db('metro4').collection('Station').findOne({"Name": variabled2},
function(err, res2) {
if(err) throw err;
variabled2 = res2._id;
console.log("id2 = ", res2._id);
myFunc(variabled);
});
異步/等待
(async function() {
let variabled2;
const res2 = await client.db('metro4').collection('Station').findOne({"Name": variabled2})
variabled2 = res2._id;
console.log("id2 = ", res2._id);
myFunc(variabled);
})()
我會建議async/await解決方案,因為它更清潔。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/408214.html
標籤:
