我有事件流向下面的程序,所以基於事件的價值我觸發不同的承諾,所以我想檢查是否它的好主意在forEach內使用承諾。如何在forEach中調用promise?
以下代碼當我有element.variables.caseIdFound
價值事件它永遠不會滿足條件。任何想法是什麼實施錯我對這些承諾是相當新的。以下代碼的任何示例都非常感謝。
camunda.js
var caseIdFound;
var processingCompleted;
function checkTicketNum(element) {
var EventCasesID;
var event;
var ticketNumber;
var CasesID;
var insertIDBEvents = [];
var event;
return new Promise(function(resolve, reject) {
event = JSON.parse(element.variables.event.value);
ticketNumber = event.body.raw.tkt;
CasesID = event.body.raw.CasesIDuuid;
controller.insertCase(ticketNumber, function(err, response) {
event.body.raw.LogIDuuid = generateUUID();
if (response.length == 0) {
completeTask('TicketNotFOund',element.id);
} else {
EventCasesID = response[0].CasesID;
if(CasesID === EventCasesID) {
caseIdFound = true;
completeTask(element.id,caseIdFound);
processingCompleted = true;
resolve(processingCompleted);
}
}
})
});
}
function postIDBCall(element) {
var event;
return new Promise(
function(resolve, reject) {
event = JSON.parse(element.variables.event.value);
controller.insertTicketAndCase2(event.body.raw, function(err, response2) {
controller.insertTicketAndCase(event.body.raw, function(err, response1) {
completeTask(event.id);
console.log("InsertIDB Result Completed",element.id);
processingCompleted = true;
resolve(processingCompleted);
})
})
});
}
module.exports = {
checkTicketNum: checkTicketNum,
generateUUID: generateUUID,
completeTask: completeTask
};
promise.js
var camunda = require('./camunda');
data.forEach(function(element) {
if (!element.variables.caseIdFound) {
camunda.checkTicketNum(element).then(function(processingCompleted) {
console.log('1st Box', processingCompleted);
});
}else if(element.variables.caseIdFound) {
console.log('END BOX IF', element.variables.caseIdFound);
camunda.postIDBCall(element).then(function(processingCompleted){
console.log('2nd Box', processingCompleted);
});
}
});
看一看['Promise.all()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) –
您應該創建一個承諾數組,然後使用Promise.all()並在那裏插入您的承諾數組。 –
請注意,promise.all將並行處理所有內容,具體取決於您的承諾正在做什麼,這可能會導致問題。藍鳥有一個值得一看的併發選項的地圖。另外一個簡單的for循環與asyn/await混合也是一個想法。 – Keith