javascript - async() 等待返回 Promise 而不是数据

标签 javascript node.js async-await ecmascript-2017

我很困惑为什么这段代码返回一个 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/

相关文章:

c# - 过滤用户输入的实践

javascript - 使用 Mongoose 对数据进行的操作不起作用

c# - 调用长时间运行的方法并继续执行其他任务

c# - TaskCompletionSource 使用

c# - 应该多广泛地使用异步/等待模式?

JavaScript :How to set a Conditional Break Point in Chrome debugger tools

javascript - VueJs v-on :event and this. $on(event, handler) 有什么区别?

javascript - 如何可靠地测量 React 组件的弹出框和标注的计算位置?

javascript - 从 webhook 解析 json

node.js - npm 安装 Angular/CLI 错误