如何在 JavaScript 中等待多次提取完成?

Tom*_*sek 5 javascript asynchronous

我需要等待两个fetch()API 调用,然后将每次获取的数据保存到不同的窗口对象。我发现这篇文章https://gomakethings.com/waiting-for-multiple-all-api-responses-to-complete-with-the-vanilla-js-promise.all-method/并尝试使用以下代码来等待API调用:

Promise.all([
    fetch('https://jsonplaceholder.typicode.com/todos/1'),
    fetch('https://jsonplaceholder.typicode.com/todos/2')
]).then(function (responses) {
    // Get a JSON object from each of the responses
    return Promise.all(responses.map(function (response) {
        return response.json();
    }));
}).then(function (data) {
    // Log the data to the console
    // You would do something with both sets of data here
    console.log(data);
}).catch(function (error) {
    // if there's an error, log it
    console.log(error);
});
Run Code Online (Sandbox Code Playgroud)

但是,将其粘贴到浏览器控制台时,不会记录结果。

代码有什么问题以及如何等待两者都得到解决?

Nic*_*ies 5

const fetchData = async () => {
  try {
    const responsesJSON = await Promise.all([
        fetch('https://jsonplaceholder.typicode.com/todos/1'),
        fetch('https://jsonplaceholder.typicode.com/todos/2')
    ]);
    const [todoOne, todoTwo] = await Promise.all(responsesJSON.map(r => r.json()));
    console.log(todoOne, 'todoOne');
    console.log(todoTwo, 'todoTwo');
  } catch (err) {
    throw err;
  }
};

fetchData();
Run Code Online (Sandbox Code Playgroud)

可能正在寻找类似的东西。