Home > Software engineering >  I am confused with async-await
I am confused with async-await

Time:06-26

My code should wait for 4-4 seconds for both the promise to execute total 8 seconds, but it is finishing in 4 seconds only. Why? Where I am thinking wrong?

// a promise
let promise1 = new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved1')}, 4000); 
});
let promise2 = new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved2')}, 4000); 
});


// async function
async function asyncFunc() {

    // wait until the promise resolves 
    let result1 = await promise1; 
    let result2 = await promise2; 
    console.log(result1);
    console.log(result2);

}

// calling the async function
asyncFunc();

//expected output

**//wait for 4 seconds first**
Promise resolved1 
**//wait for more 4 seconds**
Promise resolved2

//output
//waits for 4 seconds
Promise resolved1
Promise resolved2

CodePudding user response:

new Promise(executor)

executor, A function to be executed by the constructor. It receives two functions as parameters: resolutionFunc and rejectionFunc. Any errors thrown in the executor will cause the promise to be rejected, and the return value will be neglected. The semantics of executor are detailed below.

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

// a promise
let promise1 = () => new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved1')}, 4000); 
});
let promise2 = () => new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved2')}, 4000); 
});


// async function
async function asyncFunc() {

    // wait until the promise resolves 
    let result1 = await promise1(); 
    console.log(result1);
    let result2 = await promise2(); 
    console.log(result2);

}

// calling the async function
asyncFunc();

The promise 1 & 2 is already running when you declared. If you want result that you expect, you should code as above.

CodePudding user response:

When using async/await, your asynchronous code with begin executing, but its resolution will jump back into the synchronous code only when you use the await keyword. When you have multiple asynchronous functions, they will only execute sequentially when you have synchronous code running in between them because when you invoke the function is when the asynchronous portion of the code begins executing. In this case, the timer starts when you invoke the function, so you need to wait for the first timer to resolve before kicking off the second timer.

See this code snippet and check out the examples in this link to clarify.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

async function sequentialStart() {
  console.log('==SEQUENTIAL START==')

  // 1. Execution gets here almost instantly
  const slow = await resolveAfter2Seconds()
  console.log(slow) // 2. this runs 2 seconds after 1.

  const fast = await resolveAfter1Second()
  console.log(fast) // 3. this runs 3 seconds after 1.
}

The other issue is that when you declare your functions, you run them immediately and assign their values to variables. With minimum modification to your code, you need to set up your functions like below and only call them once you're ready to start the timer.

// a promise
let promise1 = function () {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve('Promise resolved1');
    }, 4000);
  });
};
let promise2 = function () {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve('Promise resolved2');
    }, 4000);
  });
};

// async function
async function asyncFunc() {
  // wait until the promise resolves
  let result1 = await promise1();
  console.log(result1);
  let result2 = await promise2();
  console.log(result2);
}

// calling the async function
asyncFunc();

CodePudding user response:

Simple defenation of assync await when yo declare async a function. The function will decleared as asyncronasly the default value of function is syncronasly . asyncronas function run block level(line by line) when you add await on a promise(function that return value) because of await compiler firstly resolved the promise and then run to next line of code

  • Related