Promises and async/await relationship
source link: https://bytearcher.com/articles/promises-and-async-await-relationship/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
You might have been using async/await
fluently in your programs. But once in a while, you still see glimpses of Promises. For example, when waiting for multiple asynchronous calls to finish with Promise.all()
. You might be wondering what's the relationship between Promises and async/await.
You can revisit the relationship between callbacks and Promises inthis article.
Invocation of async
function returns Promise
The first nugget of knowledge is that the invocation of an async
function returns a Promise.
You can await
result of Promise
You can await
a Promise. Your piece of code returns control back to the system. In the meantime, other parts of your program can execute. When the Promise you awaited upon settles, the runtime will continue executing your code. In case the Promise rejects, execution continues from the nearest catch
-block or .catch()
-handler.
The restriction is that you have to be inside an async
function. You're also allowed to do this on the top level when TC39 proposal top-level-await
lands in Node.
await
equivalent of .then()
Promises and async/await are interchangeable. Whenever you see an await
-statement, you can replace it with a .then()
. This is a good exercise to play in your mind when reasoning about code containing both constructs. But, when talking about program-wide conventions, it's advisable to stick to one consistently.
Similarly, .catch()
is the equivalent of a catch
-block.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK