在 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/