Using Promise.race usefully

When doing long running tasks like :-

DB query which may take long time
Reading big files
API which may take long time to complete
Waiting for some event

You may want to stop if the task is taking more time than usual to get completed. In that case…


This content originally appeared on DEV Community and was authored by Gajanan Patil

When doing long running tasks like :-

  1. DB query which may take long time
  2. Reading big files
  3. API which may take long time to complete
  4. Waiting for some event

You may want to stop if the task is taking more time than usual to get completed. In that case Promise.race can be useful.

Puppeteer project uses Promise.race to handle page/network lifecycle events with timeouts during automation.

Here's an example :-

/**
 * A utility function which throws error after timeout
 * @param timeout - timeout in seconds
 * @returns - promise which gets rejected after timeout
 */
function timer(timeout) {
    return new Promise((resolve, reject) => {
        setTimeout(reject, timeout * 1000)
    })
}

/**
 * Mock db query which take 5 seconds to complete
 * @returns - query promise
 */
function bigQuery() {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, 5 * 1000)
    })
}

// race both bigQuery and timer tasks
// `Promise.race` can take multiple promises if you want to race them all
Promise.race([
    bigQuery(),
    timer(1)
]).then(() => console.log('✅ Query successful within time limit'))
    .catch(() => console.log('❌ Query failed with timeout'))

// ==> will log '❌ Query failed with timeout'


// also try running above code by changing timer's timeout value to 6 seconds, you will get successful log

You can play with the above code here :-

/** A utility function which throws error after timeout @param timeout - timeout in seconds @returns - promise which gets rejected after timeout */ function timer(timeout) { return new Promise((resolve, reject) => { setTimeout(reject, timeout * 1000) }) } /** Mock db query which take 5 seconds to complete @returns - query promise */ function bigQuery() { return new Promise((resolve, reject) => { setTimeout(resolve, 5 * 1000) }) } // race both bigQuery and timer tasks // Promise.race can take multiple promises if you want to race them all Promise.race([ bigQuery(), timer(1) ]).then(() => console.log('✅ Query successful within time limit')) .catch(() => console.log('❌ Query failed with timeout')) // ==> will log '❌ Query failed with timeout' // also try running above code by changing timer's timeout value to 6 seconds, you will get successful log

💡 Let me know in comments other cool ideas using Promise.race

See my projects on Github.


This content originally appeared on DEV Community and was authored by Gajanan Patil


Print Share Comment Cite Upload Translate Updates
APA

Gajanan Patil | Sciencx (2021-12-22T14:16:14+00:00) Using Promise.race usefully. Retrieved from https://www.scien.cx/2021/12/22/using-promise-race-usefully/

MLA
" » Using Promise.race usefully." Gajanan Patil | Sciencx - Wednesday December 22, 2021, https://www.scien.cx/2021/12/22/using-promise-race-usefully/
HARVARD
Gajanan Patil | Sciencx Wednesday December 22, 2021 » Using Promise.race usefully., viewed ,<https://www.scien.cx/2021/12/22/using-promise-race-usefully/>
VANCOUVER
Gajanan Patil | Sciencx - » Using Promise.race usefully. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/12/22/using-promise-race-usefully/
CHICAGO
" » Using Promise.race usefully." Gajanan Patil | Sciencx - Accessed . https://www.scien.cx/2021/12/22/using-promise-race-usefully/
IEEE
" » Using Promise.race usefully." Gajanan Patil | Sciencx [Online]. Available: https://www.scien.cx/2021/12/22/using-promise-race-usefully/. [Accessed: ]
rf:citation
» Using Promise.race usefully | Gajanan Patil | Sciencx | https://www.scien.cx/2021/12/22/using-promise-race-usefully/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.