Post

Using JavaScript Promises And async/await Together

Using JavaScript Promises And async/await Together

async / await in JavaScript are syntactic sugar for Promises. Since it’s syntactic sugar, they can be used interchangeably!

Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class TestClass {
  getPromiseValue() {
    return Promise.resolve('test-promise-value');
  }

  async getAsyncValue() {
    return 'test-async-value';
  }
}

//
// Promise -> Promise
//

new TestClass().getPromiseValue().then(x => {
  console.log(`then: ${x}`);
});

//
// Promise -> `async`
//

new TestClass().getAsyncValue().then(x => {
  console.log(`then: ${x}`);
});

//
// `await` -> Promise
//

async function awaitAPromise() {
  const testClass = new TestClass();
  console.log('await: ' + await testClass.getPromiseValue());
}
awaitAPromise();

//
// `await` -> `async`
//

async function awaitAnAsync() {
  const testClass = new TestClass();
  console.log('await: ' + await testClass.getAsyncValue());
}
awaitAnAsync();

Console output

1
2
3
4
then: test-promise-value
then: test-async-value
await: test-promise-value
await: test-async-value

Note

await is only valid inside an async function!

This post is licensed under CC BY 4.0 by the author.