【发布时间】:2019-09-27 05:11:35
【问题描述】:
我有这段代码,当我运行时,它会按顺序运行“一”和“二”。
所以下面的代码可以正常工作。
(async () => {
await runit('one').then(res => {
console.info(res);
});
await runit('two').then(res => {
console.info(res);
});
})();
现在,我想在循环中做同样的事情,所以我这样做了:
const arr = ['one', 'two'];
arr.forEach(element => {
(async () => {
await runit(element).then(res => {
console.info(res);
});
})();
});
虽然看起来是相同的代码,但它不再按照顶部代码的顺序运行。
我该如何解决这个问题?
【问题讨论】:
-
您的第一个示例更像(以简化的方式):
runit('one').then(() => runit('two)) -
这是一个使用基本
for循环的解决方案:jsfiddle.net/khrismuc/a7htxg3y
标签: javascript node.js typescript async-await