Sunday, May 12, 2024
41
rated 0 times [  47] [ 6]  / answers: 1 / hits: 57365  / 7 Years ago, sat, april 15, 2017, 12:00:00

I'm trying async/await functionality. I have such code imitating a request:



const getJSON = async () => {
const request = () => new Promise((resolve, reject) => (
setTimeout(() => resolve({ foo: 'bar'}), 2000)
));

const json = await request();
return json;
}


When I use the code in this way



console.log(getJSON()); // returns Promise


it returns a Promise



but when I call this line of code



getJSON().then(json => console.log(json)); // prints { foo: 'bar' }


it prints json as expected



Is it possible to use just code like console.log(getJSON())? What don't I understand?


More From » asynchronous

 Answers
8

Every async function returns a Promise object. The await statement operates on a Promise, waiting until the Promise resolves or rejects.



So no, you can't do console.log on the result of an async function directly, even if you use await. Using await will make your function wait and then return a Promise which resolves immediately, but it won't unwrap the Promise for you. You still need to unwrap the Promise returned by the async function, either using await or using .then().



When you use .then() instead of console.logging directly, the .then() method makes the result of the Promise available to you. But you can't get the result of the Promise from outside the Promise. That's part of the model of working with Promises.


[#58141] Wednesday, April 12, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
everardo

Total Points: 406
Total Questions: 104
Total Answers: 92

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;