Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awaiting promises which is assigned to a variable

Consider the below code,

// Function which returns a promise and resolves in 2 seconds
const promiseFunction = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
};

// Asynchronous function 1
const asyncFunction1 = async() => {
    console.log(await promiseFunction());
    console.log(await promiseFunction());
    console.log(await promiseFunction());
}

// Asynchronous function 2
const asyncFunction2 = async() => {
    let a = promiseFunction();
    let b = promiseFunction();
    let c = promiseFunction();

    console.log(await a);
    console.log(await b);
    console.log(await c);
}

I am trying to understand the behaviour between asyncFunction1 and asyncFunction2 execution, the asyncFunction1 takes 2 seconds for each await (total 6) when not assigned to a variable, but asyncFunction2 resolves all the 3 promises in total 2 seconds when assigned to a variable, what happens here when it is assigned to a variable? (and we still use await with the variable).

like image 617
Tinu Jos K Avatar asked Jan 14 '20 06:01

Tinu Jos K


People also ask

How do you use await in a variable?

The await keyword is used to get a value from a function where you would normally use . then() . Instead of calling . then() after the asynchronous function, you would simply assign a variable to the result using await .

What happens when you await a promise?

Awaiting a promise to be fulfilled If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.

Does await return a promise or a value?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

How do you handle promise rejection with await?

If you use the async keyword before a function definition, you can then use await within the function. When you await a promise, the function is paused in a non-blocking way until the promise settles. If the promise fulfills, you get the value back. If the promise rejects, the rejected value is thrown.


3 Answers

The timers start when you call promiseFunction(), thus when you await a, all three timers are already running. Then when a finishes after 2 seconds, the other ones are already done too.

like image 56
Jonas Wilms Avatar answered Oct 19 '22 08:10

Jonas Wilms


The callback function passed in the Promise constructor is started to execute when the promise is created(This is the main difference between Observable and Promise). Please take a look at the first code.

// Asynchronous function 1
const asyncFunction1 = async() => {
    console.log(await promiseFunction());
    console.log(await promiseFunction());
    console.log(await promiseFunction());
}

This function waits for 2 minutes for each function so it would take 6 seconds. While the second function doesn't work the same way.

// Asynchronous function 2
const asyncFunction2 = async() => {
    let a = promiseFunction();
    let b = promiseFunction();
    let c = promiseFunction();

    console.log(await a);
    console.log(await b);
    console.log(await c);
}

It executes the 3 callback functions simultaneously. It works exactly like await Promise.all(). Therefore asyncFunction2 would be resolved in about 2 seconds.

like image 25
TopW3 Avatar answered Oct 19 '22 09:10

TopW3


For

asyncFunction1

  1. They will initiate the function one after one.That means second function was wait until first function end.
  2. Because you call the function directly on await

asyncFunction2

  1. For this case it will initiate all the function same time. so that function was trigger on immediate call. so that timer was started immediate
  2. That's why all the function executed at the same time

Check my below console .you can see the different

const promiseFunction = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
};

// Asynchronous function 1
const asyncFunction1 = async() => {
    console.log(await promiseFunction(),1);
    console.log(await promiseFunction(),1);
    console.log(await promiseFunction(),1);
}

// Asynchronous function 2
const asyncFunction2 = async() => {
    let a = promiseFunction();
    let b = promiseFunction();
    let c = promiseFunction();

    console.log(await a,2);
    console.log(await b,2);
    console.log(await c,2);
}
asyncFunction1();
asyncFunction2();
like image 1
prasanth Avatar answered Oct 19 '22 08:10

prasanth