Using async/await inside a Javascript Promise
--
What is the correct way to use async/await inside a Javascript promise?
If you're asking the question, then this short and to the point article will show you the quick and easy way to use async/await inside a JavaScript Promise.
If you’re a Javascript programmer and you use promises, then you have probably come across the need to use async/await
inside of a promise.
Does this code look familiar?
The above code is an anti-pattern. The problem is the use of async
in the promise creation. This can cause all sorts of unexpected problems.
But, I hear you ask, “How can I use await if I don’t decorate the function with async?”
The correct way to use async/await in a Javascript Promise
The secret is to create a self-invoking function and decorate that with async. Don’t worry, it’s simple, and the following code solves the above problem.
Notice in the above code, I have corrected the issue by removing async from the promise creation and created a self-invoking function and decorated it with async.
(async () => { your code goes here .... })()
A self-invoking function will do exactly what it says on the tin, it runs immediately. You don’t have to call it to make it run.
You learned a fundamental Javascript pattern today that evades many programmers. Follow me to get more snippets of wisdom.