javascript - 在 TypeScript 中使用 Promise.all 将值传递给链中的下一个处理程序

标签 javascript typescript promise es6-promise

在 JavaScript 中,有时使用 Promise.all 在异步操作链中重用一些数据很有用,如下所示:

logMeIn()
.then(token => {
  return Promise.all([
    token,
    fetchProfile(token)
  ])
})
.then(([token, profile]) => {
  return getAvatar(token, {userId: profile.id})
})
// etc...

正如我们所见,第二个 then 解析器需要第一个解析器的结果,但还需要 token。一种方法是将第二个 then 调用嵌套在第一个调用中,但这可能会变得很丑陋,并且在一个长链中,它并不比回调 hell promise 更好地设计来缓解。

使用 Promise.all() 允许我们重新使用来自早期解析器的数据并将它们传递到链中。

这一切都很好,但是当您尝试执行此操作时 TypeScript 会出错,并出现如下错误:

Argument of type '(string | Promise<Something>)[]' is not assignable to parameter of type 'IterableShim<Something | PromiseLike<Something>>'. Types of property '"es6-shim iterator"' are incompatible.
Type '() => IterableIteratorShim<string | Promise<Something>>' is not assignable to type '() => Iterator<Something | PromiseLike<Something>>'.

在 TypeScript 中有没有一种方法可以完成上述操作,最好同时保持类型安全?

最佳答案

您可以尝试显式指定返回类型:

logMeIn()
    .then<[Token, Profile]>(token => Promise.all([token, fetchProfile(token)]))
    .then(([token, profile]) => getAvatar(token, { userId: profile.id }))

关于javascript - 在 TypeScript 中使用 Promise.all 将值传递给链中的下一个处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42956952/

相关文章:

node.js - 如何在node.js中扩展q.promise?

javascript - 如何设置更大的负值以在莫里斯条形图中显示更短的条形图?

javascript - 使用 Typescript 进行 react :Unable to pass function prop to child component

javascript - Javascript '>' 运算符如何将字符与空格进行比较?

javascript - for循环中增加的数字不增加

javascript - Nodejs 一个接一个地运行异步函数

javascript - 异步等待获取未定义。怎么处理?

typescript - Angular 2调用setInterval()未定义服务形式依赖注入(inject)

Angular 7 ngFor 不更新绑定(bind)属性

typescript :以符号为键解构对象