Clean way to wait for first true returned by Promise

后端 未结 6 784
花落未央
花落未央 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:41

    You can create a new promise that resolves as soon as any given promise resolves to true like this:

    function promiseRaceTrue(promises) {
        return new Promise(function(resolve, reject) {
            promises.forEach(promise =>
                promise.then(val => val === true && resolve())
                // TODO handle resolve with value of "false"?
                // TODO handle rejection?
            );
            // TODO handle all resolved as "false"?
        });
    }
    
    var a = await promiseRaceTrue([Promise1(), Promise2(), Promise3()]);
    

    It behaves similar to Promise.race but only resolves if one of the given promises resolves with the value true instead of resolving as soon as any of the given promises either resolves or rejects.

提交回复
热议问题