How can I do setTimeout in then block? I set setTimeout there, but program just goes through and does not wait for anything.
const controller = new AbortController();
const { signal } = controller.signal;
return fetch(url, { signal })
.then((response) => {
if (response.status === 404) {
controller.abort();
setTimeout(() => controller.abort(), 5000);
}
return response;
})
.then((response) => {
console.log('in');
setTimeout(() => controller.abort(), 5000);
return response.text();
})
.catch(() => {
return Promise.reject(new Error('empty link'));
});
I tried to set settimeout in then block, in catch block, tried to use for it the function which would return promise. The logic seems simple, but somehow I don't understand something about how to connect then block and settimeout functionality.
The setTimeout() call doesn't block. If you want to "await" for x milliseconds, you can do the following:
const timeout = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
}
const doSomething = async () => {
await timeout(3000);
// after 3 seconds
}