Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES2017 Async/await functions - do they work only with promises?

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).

like image 949
Kosmetika Avatar asked Jul 08 '15 13:07

Kosmetika


People also ask

Does async-await only work with promises?

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.

Can we use async-await without promise?

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.

Are all async functions promises?

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.

Is async-await the same as promises?

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.


2 Answers

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.

like image 134
Benjamin Gruenbaum Avatar answered Oct 20 '22 22:10

Benjamin Gruenbaum


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

like image 2
Mathletics Avatar answered Oct 20 '22 22:10

Mathletics