I wanted to know , how long will await wait [and hence keeps every resource in RAM] in an async function. Consider this example:
async function my_func(some_big_sized_data){
let db_input = await gettingDBinputWhichIsDamnedSlow();
//then do some processing based on db_input and some_big_sized_data
}
Now what if DB keeps taking forever in replying. How long will await function wait and hold all those data [and hold up RAM in the process]? Is there a timeout of await too , or await can wait pratically infinitely ? [how to control this timeout time]
await
is practically a syntax sugar to consume promise. And promise can stuck pending forever, so does await. There's no builtin timeout mechanism for async/await.
Example:
async function foo() {
await new Promise(r => r);
console.log('complete');
}
If you run this foo function, that await is never gonna resolve, so it never reaches console.log('complete')
.
But await
per se doesn't hold up RAM. Whether some resources stay in RAM or got GC'ed is determined by reference count, such mechanism is not related to await
.
I said there's no builtin timeout mechanism for async/await. However, since it's just syntax sugar for promise, you can wrap your gettingDBinputWhichIsDamnedSlow
promise within another promise to create ad hoc timeout control manually.
await new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error('timeout'))
}, 10000) // wait 10 sec
gettingDBinputWhichIsDamnedSlow().then(value => {
clearTimeout(timeoutId)
resolve(value)
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With