我很困惑为什么这段代码返回一个 promise 数组,而最后一位返回实际数据(对象数组):
( async() => {
const [user, posts] = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/users'),
fetch('https://jsonplaceholder.typicode.com/posts')
]).then( ([res,res2]) => [res.json(),res2.json()]
).then( ([d1,d2]) => {
console.log(d1,d2);
});
})();
// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: Array(10)}
// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: Array(100)}
当我单独使用 fetch 时,我得到了我想要的数据:
fetch('https://jsonplaceholder.typicode.com/posts')
.then( (res) => res.json() )
.then( (data) => console.log(data)); // returns array of objects
// (100) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, ...
最佳答案
res.json()
返回另一个 promise ,因此您必须在 promise 链中返回该 promise 或使用 await
或 .then()
在那个 promise 上。因为您使用 [res.json(), res2.json()]
作为 promise 链中的返回值,所以您将 promise 隐藏在该数组中,因此 promise 链不会等待它们根本。 promise 本身成为返回结果,因此 Promise.all()
不知道它们在那里,也不会等待它们。
我建议将每个 res.json()
链接到它自己的父级:
( async() => {
const [user, posts] = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json()),
fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json())
]);
console.log(users, posts);
});
})();
然后,您将每个 res.json()
直接链接到它的源 promise ,然后 Promise.all()
将等待您。
仅供引用,我看不出有任何理由在这里使用 async/await
,因为您可以这样做:
Promise.all([
fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json()),
fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json())
]).then( ([users,posts]) => {
console.log(users, posts);
});
仅供引用,看起来一个简单的辅助函数肯定也很有用:
function fetchJSON(req) {
return fetch(req).then(res => res.json());
}
然后,你可以这样做:
Promise.all([
fetchJSON('https://jsonplaceholder.typicode.com/users'),
fetchJSON('https://jsonplaceholder.typicode.com/posts')
]).then( ([users,posts]) => {
console.log(users, posts);
});
而且,您可能希望使用所有这些选项进行错误处理,以便看到错误。您可以使用 .catch()
或使用 try/catch
包围您的 await
。
关于javascript - async() 等待返回 Promise 而不是数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614562/