typescript - 使用 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()
...
}
解决方案
你只需要离开一个返回承诺的表达式。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。
推荐阅读
- python - 处理位于不同目录中并使用 python (fastavro) 相互引用的多个 AVRO (avsc 文件)
- python - 从同一数据框中创建多个 seaborn 重叠的热图
- docusignapi - DocuSign ClickApi 端点
- flutter - 将列表中的所有数字相加或添加变化的变量列表的替代方式颤动
- python - 无法点击使用 Selenium 的网站
- reactjs - 我想通过 react spring 制作一个切换 div 但我收到了这个错误(TypeError: Object(...) is not a function)
- javascript - 如何使用 uploadType=resumable 将文件上传到谷歌驱动器 API
- node.js - Google App Engine,在 express/react 应用中部署后缓存的 index.html
- c# - 如何在使用 IoC 时使用接口扩展 UserControl
- flutter - 在颤振中将数据从函数传递到有状态小部件时遇到问题