Async/await question!

Asked 2 years ago, Updated 2 years ago, 103 views


const makeRequest = async () => {
  const value1 = await promise1();
  const value2 = await promise2(value1);
};

makeRequest();

// // do other works

I think it's a basic question, but I'm leaving a message because I'm curious!

For Promise, use the intermediate value directly within the function declared async If you used await for each of the two promises

After the value of value1 is received, the value of value2 is received, right? (Like then) Doesn't that eventually make not only the code but also the process itself synchronous?

Or you can put a promise on then and read that function quickly Are we moving on to another task? Are you processing the promise process at the same time while doing other work?

Thank you!

javascript async-await asynchronous

2022-09-20 20:53

1 Answers

Although the execution order is guaranteed within the function, the code does not change synchronously because wait is only possible within the async function.

If you look at the example below, in the case of a value that returns directly from the makeRequest function, asynchronous is not resolved, and Promise in the pending state is returned, and the value can only be used when approached asynchronously.

const makeRequest = async () => {
  const value1 = await new Promise((resolve) => resolve(2));
  const value2 = await new Promise((resolve) => resolve(value1 * value1));
  return { value1, value2 }
};

const result = makeRequest().then(res => {
    console.log(res.value1) // 2
    console.log(res.value2) // 4
});
// Executed first
console.log(result) //  Promise{<pending>}


2022-09-20 20:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.