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

613 Views Asked by At

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!

2

There are 2 best solutions below

3
On BEST ANSWER

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.

0
On

Looking at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

p1, and p2 return a promise in both examples.