13

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

7
  • It also works with thenables :-) Commented Jul 8, 2015 at 14:02
  • @Bergi are thenables a superset of promises? I'd never considered them as separate entities. Commented Jul 8, 2015 at 14:04
  • @Bergi which are promises :) Commented Jul 8, 2015 at 14:04
  • 1
    @Mathletics: Yes, exactly. Thenables are objects with a then method of unknown functionality and origin. Commented Jul 8, 2015 at 14:05
  • 1
    Yes, you can also wait for non-promise values, the spec literally says Promise.resolve will be called on the value so plain values will remain plain values and thenables will be converted to promises in a safe way. A thenable means you can assimilate promises from different libraries in await. Commented Jul 8, 2015 at 14:06

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I agree that it's easy to switch, my confusion was because of see - stackoverflow.com/questions/31294521/…
2

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

5 Comments

I just noticed that if you're using request github.com/request/request and doing await request.get('url') it will return response body. Does it mean that request lib methods not only callback based?
@Kosmetika you can not await the request library directly, but you can easily promisifyAll it and use it with promises with very low performance overhead.
@BenjaminGruenbaum but it awaits without promisifying that caused my confusion!
@Kosmetika no, it really doesn't - babeljs.io/repl/… what happened is that request was probably promisified before by a library that wraps APIs for you like bluebird.
@BenjaminGruenbaum strange days strange ways.. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.