我需要为外部请求执行带有计时器的承诺链。正如有人在类似线程中建议的那样,我使用了 async/await 并稍微重写了一下:
class myClass{
constructor(symbols){
this.downloadCsv(symbols)
}
// async/await method executing requests with timer
static async downloadCsv(symbols){
const result = [];
symbols.forEach(symbol => {
await timer(1000)
result.push(await this.downloadOneCsv(symbol['symbol']) )
}
return result
}
downloadOneCsv(symbol){
//request goes here
}
}
在执行上面的代码时,我不断收到一条错误消息,表明 async/await 无效:
await timer(1000) ^^^^^
语法错误:await 仅在异步函数中有效
我该如何解决?
首先,您不能在 a 中使用计时器,forEach
因为它的性质和调用回调函数的数量与堆栈中的数组元素数量一样多。将async
关键字添加到回调函数后,该计时器方法只会触发一次,其他时间将被跳过。我建议for of
在该数组上使用循环。
static async downloadCsv(symbols){
const result = [];
for (const symbol of symbols) {
await timer(1000)
result.push(await this.downloadOneCsv(symbol['symbol']) )
}
return result;
}
const timer = ms => new Promise(resolve => setTimeout(resolve, ms));
const arr = [1, 2, 5, 6, 7];
arr.forEach(async item => {
console.log('Before Timer');
await timer(1000);
console.log(item);
});
const timer = ms => new Promise(resolve => setTimeout(resolve, ms));
const arr = [1, 2, 5, 6, 7];
(async () => {
for (const item of arr) {
await timer(1000);
console.log(item);
}
})();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句