【问题标题】:Execute promise in synchronous batches javascript在同步批处理javascript中执行承诺
【发布时间】:2020-08-10 00:55:28
【问题描述】:

我有一个 promise 函数,它从 rows 数组接收一行到远程服务器。

const post = (row) => new Promise(resolve=>
    {    //do post then,
         resolve(response.data);
    }

所以,我想创建一个函数,它遍历数组并以恒定大小的批次对每个元素执行post。在执行下一个批次之前,当前批次应该完全解决。我怎样才能做到这一点?

【问题讨论】:

    标签: javascript promise async-await


    【解决方案1】:

    可以使用Promise.all 进行批处理,await 进行解析:

    const post = (row) => new Promise(resolve => {
        setTimeout(
            () => resolve(row.id), //for demo purpose
            1000);
    })
    
    const rows = [{
        id: 1
    }, {
        id: 2
    }, {
        id: 3
    }, {
        id: 4
    }, {
        id: 5
    }, {
        id: 6
    }, {
        id: 7
    }];
    
    const execute = async (batchSize) => {
        let currentPtr = 0;
        while (currentPtr < rows.length) {
            const results = await Promise.all(
                rows.slice(currentPtr, currentPtr + batchSize)
                .map(row => post(row))
            )
            console.log(results);
            currentPtr += batchSize;
        }
    }
    
    execute(2);

    【讨论】:

      猜你喜欢
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多