首页 > 解决方案 > 使用 async/await 链接两个 Promise

问题描述

假设我有这个需要链接两个承诺的功能

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

我需要使用双精度await来获得满足的结果post1还是多余的?

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

标签: typescriptasynchronouspromiseasync-awaitchaining

解决方案


你只需要离开一个返回承诺的表达式。fetch返回一个承诺,方法也是如此json()

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

await但是,通过混合 Promise 回调和语法,你可以变得更简洁:

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

这里fetch()返回一个带有then()方法的承诺。这里then()将返回一个在解析 JSON 内容时解析的 Promise。


推荐阅读