我刚刚开始在 React 中使用 Promise,无法解释为什么我在函数中返回 Promise,而不是我想要的数组。
代码如下:
async function pullTweets () {
let twitterRest = new TwitterRest(); //create a new instance of TwitterRest Class
var twatts = await twitterRest.pullTimeLine('google'); //pull the Google TimeLine
console.log(twatts);
return twatts;
}
let twitts = pullTweets();
console.log(twitts);
console.log(twatts);
返回正确的推文数组;然而,console.log(twitts)
正在返回一个承诺。
任何解释将不胜感激。
您需要等待
pullTweets()
,这是一个异步函数(也返回一个Promise)完成执行。
这可以通过在
await
之前使用关键字 pullTweets()
来完成:
let twitts = await pullTweets();
console.log(twitts);
您编写的代码与此等效(仅使用 Promises):
function pullTweets () {
let twitterRest = new TwitterRest();
return twitterRest.pullTimeLine('google').then((twatt) => {
// This logs the array since the promise has resolved successfully
console.log(twatt)
return twatt
})
}
let twitts = pullTweets();
// This logs a pending promise since the promise has not finished resolving
console.log(twitts);