小编Tom*_*sek的帖子

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

我需要等待两个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)

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

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

javascript asynchronous

5
推荐指数
1
解决办法
9207
查看次数

标签 统计

asynchronous ×1

javascript ×1