Search code examples
javascriptecmascript-6es6-promise

Combine Promise.race with array of data as a parameters


I have an array with 10+ data objects.

I want to check if one of checkData promise get success data with provided data parameter. I don't care which one was success, I just want to check if one from dataSet success.

Is it possible to use Promise.race in loop or map function like in below?

return Promise.race(
    dataSet.map(item => {
        checkData(item) // checkData return a Promise
    })
)
.then(...)
.catch(...)

I guess something like this could be done, If I pass array of promises to race method, it works, but I want to do this without paste 10 times(sometimes more) function that return promise.

Many thanks in advance for help.


Solution

  • Map function return new array. You have to return element in your map function. if checkData returns promises you ahve to return it in map function

    then you should have this:

    return Promise.race(
    dataSet.map(item => {
        return checkData(item) // checkData return a Promise
    }));