Nicholas M. Salvatore

Back arrow

Return quicker of multiple promises with Promise.race()

Given an array of promises, Promise.race() can be used to get only the return value of the promise that resolves the quickest. Usage is simple as the function takes an array of promises and will wait for the quickest one to resolve.

Here's an example.

function getQuickestPromiseResult() {
    const firstPromise = new Promise(resolve => setTimeout(() => {
        resolve('first')
    }, 3000))

    const secondPromise = new Promise(resolve => setTimeout(() => {
        resolve('second')
    }, 1000))

    return Promise.race([firstPromise, secondPromise])
}

(async () => {
    const quickestPromiseResult = await getQuickestPromiseResult()
    console.log(quickestPromiseResult)
})()

// Expected output: "second"