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

时间:2017-03-22 16:02:25

标签: 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调用嵌套在第一个调用内,但这可能会变得很丑陋,而且在长链中它并不比那些旨在减轻调用的回调更好。

使用Promise.all()允许我们重复使用先前解析器中的数据并将其传递给链。

这一切都很有效但是当你尝试用这样的错误执行此操作时TypeScript会翻转:

  

类型'(String | Promise< Something>)[]'的参数不可分配   到'IterableShim< Something |类型的参数   PromiseLike<东西>>”。属性类型'“ es6-shim iterator ”'   是不相容的。
      输入'()=> IterableIteratorShim< string |无极<东西>>”不能分配给'()=>类型迭代器< Something |   PromiseLike<东西>>”

在TypeScript中是否有办法可以完成上述操作,最好是在保持类型安全的情况下?

1 个答案:

答案 0 :(得分:0)

您可以尝试明确指定返回类型:

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