Len
Len

Reputation: 11

Async function won't return when the promise is resolved

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

Answers (1)

jfriend00
jfriend00

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.

  1. You call checkValue(...) and pass its arguments.
  2. The first line executes await getValue().
  3. This calls getValue() and receives a promise back.
  4. Since you're doing an await, it suspends further execution of the function and, at that point in time, the the function returns an unresolved promise.
  5. That unresolved promise is what you are looking at.
  6. Meanwhile, the rest of your code after you called getValue() continues to execute.
  7. Sometime later when the JS interpreter is done with what is was doing and goes to the event queue for the next event, it will find an event that leads to getValue() resolving its promise.
  8. At that point, the resolved value from the getValue() promise is assigned to your json variable and the execution of the checkValue() function is unpaused and continues.
  9. Then, depending upon the values in your 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

Related Questions