Antonio Santoro
Antonio Santoro

Reputation: 917

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

Upvotes: 0

Views: 1392

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187272

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.

Upvotes: 1

Related Questions