Search code examples
typescriptasynchronouspromiseasync-awaitchaining

Chaining two promises using async/await


Suppose I have this function that need to chain two promises

async function getPosts() {
  let p1 = await fetch(...)
  let p2 = await fetch(...)
  let post1 = await (await p1).json()
  let post2 = await (await p2).json()
  ...
}

Do I need to use a double await to get a fulfilled result into post1 or is it redundant?

async function getPosts() {
  let p1 = await fetch(...)
  let p2 = await fetch(...)
  let post1 = await (p1).json()
  let post2 = await (p2).json()
  ...
}

Solution

  • You only need to away an expression that returns a promise. fetch returns a promise, and so does the json() method.

    async function getPosts() {
      let p1 = await fetch(...)
      // fetch() returns a promise, `await p1` unwraps that promise.
    
      let post1 = await p1.json()
      // p1 is a fetch response, just await the `json()` method.
    }
    

    But, you can get a little cleaner by mixing promise callbacks and await syntax:

    let post1 = await fetch(...).then(res => res.json())
    

    Here fetch() returns a promise with a then() method. And then() here will return a promise that resolves when JSON content has been parse.