Clean way to wait for first true returned by Promise

后端 未结 6 742
花落未央
花落未央 2021-01-01 09:51

I\'m currently working on something where I fire out three promises in an array. At the moment it looks something like this

var a = await Promise.all([Promis         


        
6条回答
  •  一整个雨季
    2021-01-01 10:34

    OK, I will leave the accepted answer as is. But I altered it a little bit for my needs as I thought this one is a little easier to read and understand

    const firstTrue = Promises => {
        return new Promise((resolve, reject) => {
            // map each promise. if one resolves to true resolve the returned promise immidately with true
            Promises.map(p => {
                p.then(result => {
                    if(result === true){
                        resolve(true);
                        return;
                    } 
                });
            });
            // If all promises are resolved and none of it resolved as true, resolve the returned promise with false
            Promise.all(Promises).then(() => {
                resolve(Promises.indexOf(true) !== -1);
            });   
        });    
    } 
    

提交回复
热议问题