Reputation: 495
return await new Promise(function (resolve, reject) {
//some work goes here
resolve(true)
});
With Settimeout
return await new Promise(function (resolve, reject) {
//some work goes here
setTimeout(function() { resolve(true); }, 5000);
});
With setTimeout it is waiting for 5 sec even though my task completed in 1 sec. my requirement is if task complete within 5 sec then promise should resolve immediately else it will resolve at 5 sec
Upvotes: 1
Views: 683
Reputation: 2349
Here's an example using Promise.race. The idea is in Promise.race we'll do our work and race the work promise against another promise that resolves in a given time (let's say 10s for the below example),
// let's say I've to make a db connection within 10 seconds, else throw an error
const pool = await Promise.race(
[
poolPromise, // a db connection promise
new Promise((_, reject) => setTimeout(
() => {
reject("can't establish connection within 10s")
}, 10e3)
)
]);
Upvotes: 0
Reputation: 2373
You can do it like this:
return await new Promise(function (resolve, reject) {
setTimeout(function() { resolve(true); }, 5000);
let result = await someworkDone();
if (result) resolve(result);
});
Here points to note:
Upvotes: 0
Reputation: 26380
Clear the timeout when your task completes normally :
return new Promise(function (resolve, reject) {
let safetyTimeout = setTimeout(resolve, 5000);
//some work goes here
// When it's done :
clearTimeout(safetyTimeout);
resolve();
});
Upvotes: 2
Reputation: 421
Jeremy Thille answer is the best practice i think with the clearTimout.
Just cause i spended some time to write a piece a code for anyone to use, i post it, maybe it will help someone with their code experiments.
async function test() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("5 Seconds Passed");
}, 5000);
// Some work equivalent to
someWork(3000, resolve);
});
}
console.log(await test());
function someWork(time, resolve) {
// Some work goes here.
setTimeout(function () {
console.log("WORK STILL RUNNING");
resolve("INSIDE 2nd TIMEOUT");
}, time);
}
Just don't forget to implement Jeremy Thille clearTimeout.
Upvotes: 0