Search code examples
javascriptasync-awaitobject-literalecma

How the program runs when I use await in object literal?


When I write a function that returns an object, but each values of the object are constructed by resolving promises, what will I obtain at the end? I mean, what will be types of object's values?

async foo() {
    return {
        p1: await fetch('http://dummy.restapiexample.com/api/v1/employees') // FETCH REQUEST,
        p2: await fetch('http://dummy.restapiexample.com/api/v1/employees') // FETCH REQUEST
    }
}

and for such a flow, will p2 be resolved after p1? Does this code works as the same as below example:

async foo() {
    const p1 = await fetch('http://dummy.restapiexample.com/api/v1/employees') // FETCH REQUEST
    const p2 = await fetch('http://dummy.restapiexample.com/api/v1/employees') // FETCH REQUEST
    return {
        p1,
        p2
    }
}

Thank you!


Solution

  • Thank you for calling me out for asking you to clarify your question(!). I'll do my best to interpret what you're actually asking. I was tempted to simply delete this answer. It may or may not be helpful!

    If you fake up whatever "FETCH REQUEST" is, with an async method which simply prints to the console when it starts, and right before it (async) resolves, you can quite clearly see that it will complete p1 before starting p2. Running it a few times confirms this as the calls to p1 and p2 do not interleave.

    async function foo() {
        return {
            p1: await randomAsyncMethod("p1"),
            p2: await randomAsyncMethod("p2")
        }
    }
    
    async function randomAsyncMethod(which){
       console.log("starting",which);
       return new Promise( resolve =>  
          setTimeout( () => {
              console.log("resolving",which);
              resolve();
          }, Math.random() * 1000)
       );
    }
    
    
    foo();

    Now changing that to your second example, you can see the behavior is basically the same.

    async function foo() {
        var p1 = await randomAsyncMethod("p1");
        var p2 = await randomAsyncMethod("p2");
        return {
            p1,
            p2 
        }
    }
    
    async function randomAsyncMethod(which){
       console.log("starting",which);
       return new Promise( resolve =>  
          setTimeout( () => {
              console.log("resolving",which);
              resolve();
          }, Math.random() * 1000)
       );
    }
    
    
    foo();

    As for what your object will contain the return value of the fetch method is:

    A Promise that resolves to a Response object.