头图

Original: promise' in JavaScript 161356f2844831

'Return await promise' and'return promise' in JavaScript

When returning the result from the promise of the asynchronous function, you can wait for the promise to be executed and then return await promise , or you can directly return return promise :

async function func1() {
  const promise = asyncOperation();
  return await promise;
}

// vs
async function func2() {
  const promise = asyncOperation();
  return promise;
}

You will soon see that both of these expressions can be executed effectively.

However, are there situations where these expressions behave differently? Let us find out!

1. Same behavior (same behavior)

To find the difference between these two expressions ( return await promise and return promise ), an auxiliary function promisedDivision(n1, n2) will be used. This function divides 2 parameters and returns the result Promise

function promisedDivision(n1, n2) {
  if (n2 === 0) {
    return Promise.reject(new Error('Cannot divide by 0'));
  } else {
    return Promise.resolve(n1 / n2);
  }
}

If the second (divisor) parameter is 0, the function will return a Promise of reject , because division by 0 is impossible.

Okay, the auxiliary function is defined, let us divide some numbers.

The following function divideWithAwait() uses return await promiseDivision(6, 2 ) expression to return the result of 6 divided by 2 promise

async function divideWithAwait() {
  return await promisedDivision(6, 2);
}

async function run() {
  const result = await divideWithAwait();
  console.log(result); // logs 3
}
run();

In run() internal function, waiting divideWithAwait() executing the back, while the divideWithAwait() interior waiting promisedDivision(6, 2) executing the knot returns the result back. everything is normal.

Now let us try to use await promise wraps the result of the division to return promiseDivision(6, 2) :

async function divideWithoutAwait() {
  return promisedDivision(6, 2);
}

async function run() {
  const result = await divideWithoutAwait();
  console.log(result); // logs 3
}
run();

Even if the divideWithoutAwait() keyword is not used in await , the expression divideWithoutAwait() run() function still correctly calculates the division of 6/2 to 3!

In this step, you have seen that there is no difference between return await promise and return promise At least when dealing with successful Promises.

But let's explore further!

2, Different behavior (different behavior)

Now let's take another approach, especially when trying to handle execution Promise.reject . In order to make the function promiseDivision(n1, n2) return a reject of promise , we set the second parameter to 0.

Because promiseDivision(n1, 0) will now return reject , let's put the execution process in try {... } catch (error) {...} -to see if reject of promise is captured.

Well, let's use with await keyword return await promiseDivision(5, 0) expression:

async function divideWithAwait() {
  try {
    return await promisedDivision(5, 0);
  } catch (error) {
    // Rejection caught
    console.log(error); // logs Error('Cannot divide by 0')
  }
}

async function run() {
  const result = await divideWithAwait();
  console.log(result); // logs undifined
}
run();

Because division by zero is impossible, promiseDivision(5, 0) returns a promise of reject catch(error) { ... } successfully captured by promiseDivision(5, 0) thrown reject Promise of.

await about the second way to omit 061356f2844a88?

async function divideWithoutAwait() {
  try {
    return promisedDivision(5, 0);
  } catch (error) {
    // Rejection NOT caught
    console.log(error);
  }
}

async function run() {
  const result = await divideWithoutAwait();
}
run(); // Uncaught Error: Cannot divide by 0

However, this time catch(error) { ... } did not capture reject of promise .

Now you can easily see the main difference between return await promise and return promise

When being wrapped into try { ... }, the nearby catch(error) { ... } catches the rejected promise only if the promise is awaited (which is true for return await promise).

When is put try {... } catch (error) {...} time, only if promise is await modified when ( return await promise ), recent catch(error) { ... } will capture promise of reject results!

3. Conclusion (Summary)

In most cases, especially when Promise returns a successful result ( resolve ), there is not much difference between return await promise and return promise

However, if you want to capture reject promise from the return result of an asynchronous function, you should explicitly use the return await promise expression and deliberately modify it await

try {...catch(error) {...} statement can only capture the promise result reject


哇喔WEB
156 声望1.3k 粉丝

欢迎交流学习