【发布时间】:2021-03-15 18:37:01
【问题描述】:
我需要等待两次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);
});
但是,在浏览器控制台中粘贴时,结果不会被记录。
代码有什么问题以及如何等待两者都解决?
【问题讨论】:
-
如果任何请求失败怎么办?
-
你说的是哪个回报?
-
看起来不错,您将在
console.log(data);获得最终数据 -
您的代码看起来很好,并且在两个承诺都解决后打印数据。不确定你说的问题
-
在控制台中粘贴代码时,不会记录结果@VinuPrasad