Reputation: 11
I have the following code:
let checkValue = async (nodeUrl, nodeName, value) => {
let json = await getValue(nodeUrl, value);
let obj = JSON.parse(json.value.information);
for (let i = 0; i < obj.nodes.length; i++) {
if (obj.nodes[i] === nodeName) {
return Promise.resolve(true);
}
}
return Promise.resolve(false);
}
I tried to use Promise.resolve()
to process the returned Promise value, but I still get Promise { <pending> }
return. Why is this happening?
Upvotes: 0
Views: 363
Reputation: 707158
Let's explain a bit what happens in an async
function.
First off, all async functions return a promise. Always. You will always need to use .then()
or await
to get the value from the returned promise.
Second, Here's the sequence of events in your function.
checkValue(...)
and pass its arguments.await getValue()
. getValue()
and receives a promise back.await
, it suspends further execution of the function and, at that point in time, the the function returns an unresolved promise.getValue()
continues to execute.getValue()
resolving its promise.getValue()
promise is assigned to your json
variable and the execution of the checkValue()
function is unpaused and continues. for
loop, your function will finish by returning a resolved promise. Note, there is no reason to do return Promise.resolve(true)
or return Promise.resolve(false)
. Just return true
or return value
is all that is required. Whatever the return
value is from an async
function becomes the resolved value of the promise that was already returned from that function. The interpreter does that for you.I tried to use Promise.resolve() to process the returned Promise value, but I still get
Promise { <pending> }
return. Why is this happening?
First, you get a promise because all async
functions return a promise.
Second, it's unresolved at the time you examine it because the function was suspended at the first await
and that's when the async
function actually returned the promise and it is, at that point, unresolved because the function has not yet finished executing (due to the await
). See step 4 above.
Upvotes: 2