Skip to content

Instantly share code, notes, and snippets.

@rubystream
Created October 2, 2016 21:16
Show Gist options
  • Save rubystream/cd7be4af6bb4da462610dd4e1a1c6538 to your computer and use it in GitHub Desktop.
Save rubystream/cd7be4af6bb4da462610dd4e1a1c6538 to your computer and use it in GitHub Desktop.
Promise.race timeout
function delay(time) {
return new Promise(fulfill => {
setTimeout(fulfill, time);
});
}
Promise.race([longRunningPromise, delay(time).then(function () {
throw new Error('Operation timed out');
})])
.then(value => { console.log(value); })
.catch(reason => { console.log(reason); });
@tianyk
Copy link

tianyk commented Aug 29, 2018

function timeout(time) {
    return new Promise((_, reject) => {
        setTimeout(() => {
            reject(new Error('Operation timed out'));
        }, time);
    });
}

Promise.race([longRunningPromise, timeout(time)])
    .then(value => { console.log(value); })
    .catch(reason => { console.log(reason); });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment