[英]Node js, how to run a code sync after a loop
這是我的代碼,其中我嘗試使用for循環更新數據庫(MongoDB)的某些文檔。 但是我想在循環完成后運行下一個代碼,例如,我想使用一些在循環完成后計算的變量。 我該如何使用回調,promise等來做到這一點?
numPktUpdated = 0;
for (key in InvoicesPUT) {
Invoice.findOneAndUpdate({ InvoiceNumber: InvoicesPUT[key].InvoiceNumber }, InvoicesPUT[key]).exec()
.then((doc) => {
console.log("Update Succeeded")
numPktUpdated = numPktUpdated + 1;
})
.catch((err) => {
return resp.send(JSON.stringify({
"status": "error",
"message": "DB Error while Updating: Wrong Packet"
}));
console.log(err);
})
}
resp.send(numPktUpdated);
此處numPktUpdated = 0發送給客戶端,盡管循環后的實際值不一樣。
謝謝。
嘗試將代碼放入函數中,然后使用異步運行它
async function forLoopFunction(args){//here is a for loop
}
let ret = await forLoopFunction(args);
您應該能夠使用Promise.all()
做到這一點:
Promise.all(InvoicesPUT.map(InvoicePUT => {
return Invoice.findOneAndUpdate({
InvoiceNumber: InvoicePUT.InvoiceNumber
}, InvoicePUT).exec()
.then(doc => {
console.log("Update Succeeded");
numPktUpdated += 1;
})
}))
.catch(err => {
return resp.send(JSON.stringify({
"status": "error",
"message": "DB Error while Updating: Wrong Packet"
}));
console.log(err);
})
.then(() => {
// What you want to do after the loop ...
})
如果您使用的是Node v7.6的舊版本,該版本帶來了對async / await模式的支持,則可以使用一個簡單的Promise :
function updateDocs() {
return new Promise(function(resolve, reject) {
numPktUpdated = 0;
for (key in InvoicesPUT) {
Invoice.findOneAndUpdate({ InvoiceNumber: InvoicesPUT[key].InvoiceNumber }, InvoicesPUT[key]).exec()
.then((doc) => {
console.log("Update Succeeded")
numPktUpdated = numPktUpdated + 1;
resolve(numPktUpdated);
})
.catch((err) => {
console.log(err);
reject(err);
return resp.send(JSON.stringify({
"status": "error",
"message": "DB Error while Updating: Wrong Packet"
}));
})
}
});
}
updateDocs().then(function(numPktUpdated) {
resp.send(numPktUpdated);
})
.catch(function(err) {
// handle error
});
謝謝,它僅需進行少量修改即可:
Promise.all(InvoicesPUT.map(invoice => {
return Invoice.findOneAndUpdate({InvoiceNumber: invoice.InvoiceNumber}, invoice).exec()
.then((doc) => {
console.log("Update Succeeded")
numPktUpdated = numPktUpdated + 1;
})
}))
.catch((err) => {
return resp.send(JSON.stringify({
"status": "error",
"message": "DB Error while Updating: Wrong Packet"
}));
console.log(err);
})
.then((resolve) => {
return resp.send(JSON.stringify({
"status": "succed",
"LastSavedGUID": 654323,
"SyncDate": 1,
"pagenumber": numPktUpdated
}));
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.