【发布时间】:2019-02-06 21:37:25
【问题描述】:
这是我的问题:
我的主要功能:
const mainFunction = () => {
const reports = JSON.parse($sessionStorage.datas);
// reports contains array of objects.
// consider i have two objects inside one array, so the loop will execute two times now
reports.forEach((item) => {
this.openReport(item);
});
};
mainFunction();
openReport函数:
this.openReport = (report) => {
console.log('openReport working');
// some async functions will be here
// ajax calls
this.openTab(report);
};
openTab 函数:
this.openTab = (report) => {
console.log('handleOpenTab function working');
}
输出:
// Now i have two objects, so forEach works two times.
'openReport working'
'openReport working'
'handleOpenTab function working'
'handleOpenTab function working'
我的预期输出:
'openReport working'
'handleOpenTab function working'
'openReport working'
'handleOpenTab function working'
如何做到这一点?我无法在我的 forEach 函数中使用异步等待,因为使用的是旧节点版本。
如果可以使用 async/await 来解决这个问题,我会尝试升级我的节点版本。
【问题讨论】:
-
你需要使用 Promise。你的旧节点版本仍然支持 Promises,对吧?
-
对每个 ajax 调用使用时间戳,并包含与选项参数相同的内容。收到回复后与时间戳进行交叉检查
-
@TKoL 哪个函数需要转换为 promise?
-
如何使用 async/await 来解决这个问题?如果我找到解决方案,我将升级节点版本。
-
@MohamedSameer 您的 OpenReport 函数说它执行 ajax 调用和其他操作,因此该函数应该返回一个在 ajax 调用完成和
this.openTab被调用后解析的承诺。然后你必须调整 mainFunction 来使用 Promise,我个人会使用递归循环
标签: javascript angularjs asynchronous promise