How to set maximum execution time for a Promise await?

The code below will give you some idea:

function doSomething(maxExecutionTime) {
    return new Promise(resolve => {
        setTimeout(() => resolve(true), 2000);  // this setTimeout simulates your async action which sould not exced maxExecutionTime
        setTimeout(() => resolve(false), maxExecutionTime);
    });
}

async function someFunc(maxExecutionTime) {
    var exced = await doSomething(maxExecutionTime);
    if (exced) {
        console.log("Doesn't exced max time");
    } else {
        console.log("Exced max time");
    }
}

someFunc(1000);
someFunc(3000);

You can use Promise.race() which will immediately resolve/reject when the first promise in its iterable resolves or rejects. E.g.

   
const longTask = () => new Promise(resolve =>
  setTimeout(() => resolve("Long task complete."), 300))

const timeout = (cb, interval) => () =>
  new Promise(resolve => setTimeout(() => cb(resolve), interval))

const onTimeout = timeout(resolve =>
  resolve("The 'maybeLongTask' ran too long!"), 200)

Promise.race([longTask, onTimeout].map(f => f())).then(console.log)

The only issue is you can't really cancel the 'longTask' just because of its long execution. In theory, you'd either set some flag (to tell it not to continue onto the next stage of its pipeline), or design your application with the consequences of the promise in mind.

See what happens when you swap the 200 and 300 intervals.

Edit: Per spsaucier's comment, I've delayed the execution of each promise until the Promise.line line.

Tags:

Javascript