简体   繁体   English

Promise.all()基于返回Promises的函数

[英]Promise.all() based on functions returning Promises

I am trying to use Promise.all() with Promises encapsulated on functions: 我试图将Promise.all()与封装在函数上的Promises一起使用:

function fn1(val){

    return new Promise((resolve, reject) => {  

       /* promise body */        
    });    
}


function fn2(val){

    return new Promise((resolve, reject) => {  

       /* promise body */        
    });    
}



fn1(data)
.then((val) => fn2(val))
.catch((error) => alert(error)



Promise.all([fn1, fn2]).then(() => alert("Done!"))

This seems not possible as the Promise.all([fn1, fn2]) executes directly instead of waiting for the promises to success. 这似乎是不可能的,因为Promise.all([fn1, fn2])直接执行,而不是等待成功的承诺。

I know I could just chain another .then() to the thenable structure, but I wonder if there is any way of using Promise.all() on a context where Promises are contained into functions. 我知道我可以将另一个.then .then()thenable结构,但是我想知道是否有任何方法可以在将Promises包含在函数中的上下文中使用Promise.all()

Promise.all takes an Array of Promise s. Promise.all需要一个Promise Array

Since your functions return Promises you can call the functions while declaring the Promise.all Array and they will be replaced by the Promises. 由于您的函数返回Promises,因此您可以在声明Promise.all数组的同时调用函数,它们将被Promises 代替

 // error handling (reject/catch) omitted for brevity. function fn1 (val) { return new Promise(resolve => { resolve('foo ' + val) }) } function fn2 (val) { return new Promise(resolve => { resolve('bar ' + val) }) } Promise.all([fn1(1), fn2(2)]) .then(result => console.log(result)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM