当您需要将结果附加到位于函数作用域顶层的数组时,链接某些内容的正确方法是什么?
function run() {
let array = []
let input = 'object'
promiseA(input)
.then((result) => {
array.push(result)
})
promiseB(input)
.then((result) => {
array.push(result)
})
console.log(array.join(' '))
}
顺序对于我的应用程序来说并不重要,如果这被认为是最佳实践,我可以将其并行化。它实际上只是检查条件,没有异步调用来从 API 或类似的东西获取结果。
最佳答案
您应该使用 Promise.all 等待 Promise A 和 Promise B 完成。 Promise.all 将收到一组结果(来自每个 Promise),然后您可以使用它们。
你可能有这样的东西:
var promiseA = doSomethingThatReturnsPromise(input);
var promiseB = doSomethingThatReturnsPromise(anotherInput);
Promise.all([promiseA, promiseB]).then(function(resultsArray) { // do something });
关于javascript - 链接这个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49460405/