javascript - Will a promise exit the execution prematually without await? - Stack Overflow

Here is how the await is used:The keyword await makes JavaScript wait until that promise settles and re

Here is how the await is used:

The keyword await makes JavaScript wait until that promise settles and returns its result.

If app doesn't want to await until a promise settles and returns (such as update non-critical backend database), is it OK to call the promise without await? May a promise called without await exit prematurely before the promise is pletely finished?

Here is how the await is used:

The keyword await makes JavaScript wait until that promise settles and returns its result.

If app doesn't want to await until a promise settles and returns (such as update non-critical backend database), is it OK to call the promise without await? May a promise called without await exit prematurely before the promise is pletely finished?

Share Improve this question edited Feb 1, 2021 at 3:15 user202729 4,0333 gold badges29 silver badges47 bronze badges asked Jan 20, 2021 at 18:54 user938363user938363 10.4k41 gold badges159 silver badges328 bronze badges 8
  • What is "app" in your question? Promise does not really care whether it's awaited or not. Regardless of anything promise constructor callback runs entirely. – zerkms Commented Jan 25, 2021 at 6:50
  • Do you want to keep timeout for certain operation in your promise OR do you want the cancel the promise itself? If yes, Promise cancelling is not yet supported, you might need to introduce timeouts to handle. – Naren Commented Jan 25, 2021 at 7:04
  • "May a promise called without await exit prematurely before the promise is pletely finished?" Exit from what? Could you clarify your question with an example (be it pseudo-code if necessary) of what you are struggling with? It's quite unclear if you want to simply call a method that returns a Promise without using that Promise at all, or if you want to have some way to cancel the asynchronous task that got wrapped in the Promise. – Kaiido Commented Jan 25, 2021 at 7:52
  • It is React Native mobile app. For better user experience, some operation such as update non-critical backend database doesn't have to wait for return value of promise. Skip await makes sense as long as the promise will not be exit prematurely without await keyword. – user938363 Commented Jan 25, 2021 at 7:57
  • 1 You mean like it would timeout itself without doing what it was supposed to do? Nope that won't happen. And yes, you can very well make calls to methods that return Promises (such as fetch) without having to actually await it if you don't care about the result of that method (though it would probably make for a bad design to not catch errors). Also, please edit your question so that what you want is stated more clearly, current answers seem to have missed the point pletely. – Kaiido Commented Jan 25, 2021 at 8:12
 |  Show 3 more ments

3 Answers 3

Reset to default 6

A promise is just a way of encapsulating the idea of getting some value in the future.

You don't "call" a promise.

You can either use a promise directly

const somePromise = someFunctionThatReturnsAPromise()
somePromise.then(functionToCallWhenValueIsAvailable);

function functionToCallWhenValueIsAvailable(value) {
  console.log(value);
}

Or you can use it via await

const value = await someFunctionThatReturnsAPromise();
console.log(value);

await just makes the code simpler but it's doing the same thing

Roughly Yes, You can do. await is when you need an asynchronous process.

If you just need to execute and don't need to wait for the process, then You can just call promise without await. Then the process won't wait and keep working for the next things.

However, be sure to handle rejection for this. You may need Promise.catch. Otherwise, You would see the unhandled promise rejection error when there is rejection from promise and it may be hard to debug.

Let's say p is an object of type Promise. A promise is usually returned by a function that started an asynchronous operation. The function returns (the promise) immediately while the asynchronous operation is still running in background.

The promise object is used by the calling code to know when the asynchronous operation pletes.

This can be done in two ways:

  1. Using .then()/.catch(). This lets the main script continues and when the asynchronous operation pletes a callback provided by the main script is invoked to learn about the way the promise has been fulfilled.

    p.then((v) => console.log(`the async operation pleted successfully and returned '${v}'`))
     .catch((err) => console.log(`the async operation failed with error: ${err}`));
    
  2. Using await and try/catch. This way the main script is paused until the asynchronous operation pletes. It resumes after the await statement on success or with the catch block if the async code throws an exception (the promise is rejected).

    try {
      v = await p;
      console.log(`the async operation pleted successfully and returned '${v}'`);
    } catch (err) {
      console.log(`the async operation failed with error: ${err}`);
    }
    

Neither of these methods affects the way the async operation is executed. It does its job in the background and, at some point, it pletes (with success or failure).

If neither of these synchronization methods is used then the main code loses any way to learn about the faith of the asynchronous operation.

If the async operation pletes with success, nobody knows when this happens and the value it returns is lost.

If it throws an exception then there is no way to catch it and, at least in Node.js, it terminates the execution of the entire script (because it is an unhandled exception and the interpreter does not know if it's safe to continue in such situations.)

Using one of the methods above, when an exception is thrown by the asynchronous code, the handler registered with .catch() (in the .then()/.catch() method) or the code block after catch(err) (in the await/try/catch method) is executed and the exception is passed to it (as err). It's up to these pieces of code to terminate the execution of the program or log the error and continue (as they do in my examples above).

Read more about promises and await

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745246714a4618441.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信