xxxxxxxxxx
const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time));
await sleep(500)
// Do something after the sleep!
xxxxxxxxxx
const timeout = function (s) {
return new Promise(function (_, reject) {
setTimeout(function () {
reject(new Error(`Request took too long! Timeout after ${s} second`));
}, s * 1000);
});
};
xxxxxxxxxx
const promiseWithTimeout = promise => {
let timeoutId;
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(() => {
reject(new Error('Request timed out'));
}, 4000); })
return {
promiseOrTimeout: Promise.race([promise, timeoutPromise]),
timeoutId, };
};