Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  15] [ 1]  / answers: 1 / hits: 15386  / 7 Years ago, fri, december 8, 2017, 12:00:00

How would you wait for a Promise to resolve/reject, for a maximum execution time ? The code below is obviously wrong, it's just to explain what I'm trying to achieve. I'm clueless.



await doSomething();
if ( executionTime > maxExecutionTime ) {
doSomethingElse();
}


This is not for a bluebird promise.


More From » javascript

 Answers
36

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.


[#55721] Wednesday, December 6, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;