I am just beginning to work with promises in React and cannot explain why I am returning a promise in a function and not the array I want.
The code is as follows:
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);
The console.log(twatts); is returning the correct array of tweets; however, the console.log(twitts) is returning a promise.
Any explanation would be greatly appreciated.
Thanks
You need to wait for pullTweets()
which is an asynchronous function (that returns a Promise as well) to finish executing.
This can be done by using the keyword await
before pullTweets()
:
let twitts = await pullTweets();
console.log(twitts);
The code you wrote is equivalent to this (using only 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.