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

Javascript 在TypeScript中使用Promise.all将值传递给链中的下一个处理程序,javascript,typescript,promise,es6-promise,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... 正如我们所看到

在JavaScript中,在中使用
Promise有时很有用。all
在异步操作链中重复使用一些数据,如:

logMeIn()
.then(token => {
  return Promise.all([
    token,
    fetchProfile(token)
  ])
})
.then(([token, profile]) => {
  return getAvatar(token, {userId: profile.id})
})
// etc...
正如我们所看到的,第二个
然后的
解析器需要第一个解析器的结果,但仍然需要
令牌。一种方法是将第二个
调用嵌套在第一个
调用中,但这可能会变得很难看,而且在一个长链中,它并不比回调地狱承诺的要缓解的地方更好

使用
Promise.all()

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

类型为“(string | Promise)[]”的参数不可赋值 到类型为“IterableShim”的参数。属性“es6垫片迭代器”的类型 不兼容。
类型“()=>IterableTeratorShim”不可分配给类型“()=>Iterator”


TypeScript中是否有一种方法可以实现上述操作,最好是在保留类型安全性的情况下?

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

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

请注意,对于这个一般性问题,有很多解决方案。TypeScript是否已经支持
async
/
await
?@Bergi确实支持,尽管当TypeScript获得