【问题标题】:Promise.all() with dynamically sized array of requests using awaitPromise.all() 与使用 await 的动态大小的请求数组
【发布时间】:2021-01-09 15:08:34
【问题描述】:

我是 JavaScript 和 Promises 的新手。我需要使用Promise.allawait 发送一系列请求。不幸的是,我不知道数组的大小,所以它需要是动态的。该数组将是请求。例如:

let arrayOfApiCreateRecords = [];
arrayOfApiCreateRecords.push(apiCreateRecords(req, { clientHeaders: headers, record }));
let responses = await Promise.all( arrayOfApiCreateRecords );

我试着这样写我的代码,但我似乎被卡住了。是否可以使用Promise.all 重写代码并等待动态请求数组?请指教。以下是我所拥有的:

'use strict';

const { apiCreateRecords } = require('../../../records/createRecords');

const createRecords = async (req, headers) => {
  let body = [];
  let status;
  for(let i = 0; i < req.body.length; i++) {
    let r = req.body[i];
    let record = {
      recordId: r.record_Id,
      recordStatus: r.record_status,
    };
    const response = await apiCreateRecords(req, { clientHeaders: headers, record });
    status = (status != undefined || status >= 300) ? status : response.status;
    body.push(response.body);
    };
  return { status, body };
};

module.exports = {
  createRecords,
};

【问题讨论】:

  • 这正是Promise.all() 的用途。数组可以是任意大小。
  • 在循环中将 Promise 推送到数组中,然后在循环完成时调用 Promise.all()
  • @Barmar 这不会调用所有的承诺吗?我希望他们一次被处决。
  • “电话承诺”? wdym?
  • Promise 在你调用异步函数时开始执行。 Promise.all() 等待全部解决。

标签: javascript node.js async-await es6-promise


【解决方案1】:

好,我就用fetch API来演示Promise.all()的用法

正常使用(用于一个fetch 呼叫)

let user = { username: 'john.doe', password: 'secret' };

try{
    let res = await fetch('https://example.com/user/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(user)
    })

    console.log('User creation response: ', res);
}
catch(err){
    console.error('User creation error: ', err);
}

现在让我们使用Promise.all()

const users = [
    { username: 'john.doe', password: 'secret' },
    { username: 'jane.doe', password: 'i-love-my-secret' }
];

const requests = [];

// push first request into array
requests.push(
    fetch('https://example.com/user/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(user[0])
    })
);

// push second request into array
requests.push(
    fetch('https://example.com/user/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(user[1])
    })
);

try{
    const responses = await Promise.all(requests);

    console.log('User creation responses: ', responses);
}
catch(err){
    console.log('User creation error: ', err);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 2014-07-21
    • 2020-09-19
    • 2015-08-16
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 2021-08-21
    相关资源
    最近更新 更多