编程语言
首页 > 编程语言> > JavaScript / TypeScript-承诺循环不会等待

JavaScript / TypeScript-承诺循环不会等待

作者:互联网

我有一个100个承诺的循环.我想同时处理其中的10个,然后打印一条语句,然后继续并行处理下10个.但是,它不会等待每10个诺言完成它们的执行.

const promises = [];
for (let i = 1; i <= 100; i ++) {

   const blockPromise = this.web3.eth.getBlock(i).then((block: any) => {
        winston.info("Processing block " + i);
   }).catch((err: Error) => {
        winston.error(err);
   });

   promises.push(blockPromise);

   if (i % 10 === 0) {
       Promise.all(promises).then(() => {
            winston.info("+++ Processed " + 10 + " blocks");
       }).catch((err: Error) => {
            winston.error(err);
       });
   }

我的期望是这样的:

Processing block 1
Processing block 3
Processing block 7
Processing block 2
Processing block 4
Processing block 5
Processing block 6
Processing block 9
Processing block 10
Processing block 8
+++ Processed 10 blocks
Processing block 12
...

但是,它混乱地混杂在一起.我究竟做错了什么?任何帮助表示赞赏.

解决方法:

由于您每次尝试处理10个诺言,因此您可以在每10个诺言之后等待,否则会失败吗?

var promises = []; // You are mutating it so better not be a const
var blockPromise = null;
for (let i = 1; i <= 100; i ++) {

 blockPromise = this.web3.eth.getBlock(i).then((block: any) => {
      winston.info("Processing block " + i);
 }).catch((err: Error) => {
      winston.error(err);
 });

 promises.push(blockPromise);

 if (i % 10 === 0) {
     await Promise.all(promises);
     promises = [] // clear the processed promises as well
     winston.info("+++ Processed " + 10 + " blocks");
 }
}

标签:ecmascript-6,asynchronous,promise,es6-promise,javascript
来源: https://codeday.me/bug/20191025/1929760.html