I started using async/await
ES7 functions in my js applications (transpiled by Babel).
Correct me if wrong, but do they work only with Promises? If yes, this means that I need to wrap regular callback functions into Promises (what I'm currently doing btw).
Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.
This rule applies when the await operator is used on a non-Promise value. await operator pauses the execution of the current async function until the operand Promise is resolved.
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
Promise creation starts the execution of asynchronous functionality. await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves. So, if an asynchronous activity has already started, await will not have any effect on it.
The current (and likely final) async/await proposal awaits promises and desugars into something like bluebird's Promise.coroutine
with await
playing the part of yield
.
This makes sense, as promises represent a value + time and you're waiting for that value to become available. Note await
also waits for promise like constructs in all other languages that include it like C# or Python (3.5+) .
Note that converting callback APIs to promises is very easy, and some libraries offer tools to do so in a single command. See How to convert an existing callback API to promises for more details.
Yes, you await
a promise.
async function myFunction() {
let result = await somethingThatReturnsAPromise();
console.log(result); // cool, we have a result
}
http://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With