Fetch, then and setTimeout - javascript

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
}

Related

Perform an action after a promise.then callback

I'm trying to encapsulate some intialization / clean up code in a single Promise. What I want if to execute some code, execute the then and then execute some more code. This is what I came up with:
function initialize() {
let callback;
console.log('intialization');
const promise = new Promise(resolve => callback = resolve);
new Promise(async () => {
await callback();
await promise;
console.log('cleanup');
});
return promise;
}
initialize().then(() => console.log('execute then'));
which gives me the following output in the terminal:
initialization
execute then
cleanup
- Promise {<fulfilled>: undefined}
All good so far. However, when we make the callback async, it no longer works.
initialize().then(
async () => {
await new Promise(resolve => {
setTimeout(
() => {
console.log('execute then');
resolve();
},
10000
)
})
}
);
gives me this output:
initialization
cleanup
- Promise {<pending>}
execute then
I would have expected it to look like this:
initialization
- Promise {<pending>}
execute then
cleanup
How can I fix this? Is this even possible at all?
You can accept a callback that defines an asynchronous operation. Then it can be inserted into the middle of an promise chain:
const delayMessage = (message, ms) =>
new Promise(resolve => setTimeout(() => {
console.log(message);
resolve();
}, ms));
async function somethingAsync() {
console.log('intialization');
}
function initialize(callback) {
return somethingAsync()
.then(callback)
.then(() => {
console.log('cleanup');
});
}
const middleOfProcess = () => delayMessage('execute then', 2000);
initialize(middleOfProcess);
It works even if there are multiple async steps to do in between, since you can simply chain them together:
const delayMessage = (message, ms) =>
new Promise(resolve => setTimeout(() => {
console.log(message);
resolve();
}, ms));
async function somethingAsync() {
console.log('intialization');
}
function initialize(callback) {
return somethingAsync()
.then(callback)
.then(() => {
console.log('cleanup');
});
}
const middleOfProcess = () => delayMessage('execute then1', 2000)
.then(() => delayMessage('execute then2', 2000))
.then(() => delayMessage('execute then3', 2000));
initialize(middleOfProcess);
The same can be done using async/await syntax:
const delayMessage = (message, ms) =>
new Promise(resolve => setTimeout(() => {
console.log(message);
resolve();
}, ms));
async function somethingAsync() {
console.log('intialization');
}
async function initialize(callback) {
await somethingAsync();
await callback();
console.log('cleanup');
}
const middleOfProcess = async () => {
await delayMessage('execute then1', 2000);
await delayMessage('execute then2', 2000);
await delayMessage('execute then3', 2000);
};
initialize(middleOfProcess);

polling on a promise to have always fresh data

i'm trying to fetch an endpoint that return a json object to display the result in my app.
this json return a list of online users, so i need to refresh this data every X seconds/minutes.
i've writed this code:
function getJustBlabData(url) {
return new Promise(resolve => {
const getData = fetch(url);
resolve(getData)
})
}
getJustBlabData('https://justblab.com/baxf/widget.php?q=online_usr')
.then((res) => res.json()
.then((data) => {
this.justBlab = data
this.loading = false
console.log(this.justBlab)
})
)
ive tried with setInterval like:
function getJustBlabData(url) {
return new Promise(resolve => {
setInterval(() => {
const getData = fetch(url);
resolve(getData)
}, 1000)
})
}
but i'm doing something wrong, but what?
Firstly, use fetch directly, since your getJustBlabData function is essentially just return fetch(url) wrapped in a new Promise - but since fetch already returns a Promise, there is no need for that code at all
i.e.
function getJustBlabData(url) {
return new Promise(resolve => {
const getData = fetch(url);
resolve(getData)
})
}
getJustBlabData(url).then ....
is equivalent (but in a lot of ways worse for error handling) to
fetch(url).then ....
If you want to do something every X seconds, do the whole thing in the interval
Like this
setInterval(() => {
this.loading = true;
fetch('https://justblab.com/baxf/widget.php?q=online_usr')
.then((res) => res.json())
.then((data) => {
this.justBlab = data;
this.loading = false;
console.log(this.justBlab);
});
}, 1000);
Now, this.justBlab gets updated every second
Note: Also, I've flattened your .then pyramid into a .then chain
to address the situation where requests could take longer than a second
(() => {
const processBlab = () => {
this.loading = true;
fetch('https://justblab.com/baxf/widget.php?q=online_usr')
.then((res) => res.json())
.then((data) => {
this.justBlab = data;
this.loading = false;
console.log(this.justBlab);
setTimeout(() => processBlab(), 1000);
});
processBlab();
})();
Only reason I put that all in a IIFE is to preserve this - as there is no context in the question as to what this is
You can use a promise to create a "wait" function and the restart the process again (get a new set of data) once that completes.
Here I used a 5 second delay between each cycle.
Doing it this way, if the server takes 10 seconds to reply this will do a new request 5 seconds after that response and avoids piling up requests.
let delayMSTime = 5000;
let howMany = 1;
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
function getJustBlabData(url) {
return new Promise(resolve => {
const getData = fetch(url);
resolve(getData);
})
}
function GoGetEm(myDelay) {
getJustBlabData('https://justblab.com/baxf/widget.php?q=online_usr')
.then((res) => res.json())
.then((data) => {
this.justBlab = data;
this.loading = false;
console.log(this.justBlab);
}).then(() => {
console.log("sleeeping for the "+howMany+" time:" + myDelay);
sleep(myDelay).then(() => {
howMany++;
GoGetEm(myDelay);
console.clear();
});
});
}
GoGetEm(delayMSTime);

How to set a time limit to a method in NodeJs?

I have a use case, where I am doing an external API call from my code,
The response of the external API is required by my code further on
I am bumping into a scenario, where the external API call at times takes far too long to return a response,
casing my code to break, being a serverless function
So I want to set a time limit to the external API call,
Where if I don't get any response from it within 3 secs, I wish the code to gracefully stop the further process
Following is a pseudo-code of what I am trying to do, but couldn't figure out the logic -
let test = async () => {
let externalCallResponse = '';
await setTimeout(function(){
//this call sometimes takes for ever to respond, but I want to limit just 3secs to it
externalCallResponse = await externalCall();
}, 3000);
if(externalCallResponse != ''){
return true;
}
else{
return false;
}
}
test();
Reference -
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SSM.html#getParameters-property
I'm using AWS SSM's getParameters method
You cannot await setTimeout as it doesn't returns a Promise.
You could implement a function that returns a Promise which is fulfilled after 3 seconds.
function timeout(seconds) {
return new Promise((resolve) => {
setTimeout(resolve, seconds * 1000)
});
}
You can await the above function in your code passing the number of seconds you want to wait for
let test = async () => {
let externalCallResponse = '';
setTimeout(async () => {
externalCallResponse = await externalCall();
}, 0);
await timeout(3); // wait for 3 seconds
if(externalCallResponse != '') return true;
else return false;
}
Following code snippet demonstrates the usage of timeout function written above. It mocks a api request that returns a response after 4 seconds.
function timeout(seconds) {
return new Promise(resolve => {
setTimeout(resolve, seconds * 1000);
});
}
function apiRequest() {
return new Promise(resolve => {
setTimeout(() => resolve('Hello World'), 4000);
});
}
let test = async () => {
let externalCallResponse = '';
setTimeout(async () => {
externalCallResponse = await apiRequest();
}, 0);
await timeout(3); // wait for 3 seconds
if (externalCallResponse != '') return true;
else return false;
};
test()
.then(res => console.log(res))
.catch(err => console.log(err.message));
you can use something like this, I created a function that return a promise then I used this promise.
let test = async () => {
return promiseTimeout()
}
const promiseTimeout = () => {
return new Promise(async (resolve, reject) => {
setTimeout(function () {
let externalCallResponse=""
externalCallResponse = await externalCall();
if (externalCallResponse != '') {
return resolve(true);
}
else {
return resolve(false);
}
}, 3000);
})
}
test().then(result=>{
console.log(result);
});
You could do something like this:
const timeout = async (func, millis) => {
return new Promise(async (resolve, reject) => {
setTimeout(() => reject(), millis);
resolve(await func());
});
}
timeout(() => doStuff(), 3000)
.then(() => console.log('worked'))
.catch(() => console.log('timed out'));
Tests:
const timeout = async (func, millis) => {
return new Promise(async (resolve, reject) => {
setTimeout(() => reject(), millis);
resolve(await func());
});
}
const doStuffShort = async () => { // Runs for 1 second
return new Promise((resolve) => setTimeout(() => resolve(), 1000));
}
const doStuffLong = async () => { // Runs for 5 seconds
return new Promise((resolve) => setTimeout(() => resolve(), 5000));
}
timeout(() => doStuffShort(), 3000)
.then(() => console.log('1 worked'))
.catch(() => console.log('1 timed out'));
timeout(() => doStuffLong(), 3000)
.then(() => console.log('2 worked'))
.catch(() => console.log('2 timed out'));

How to correctly resolve a promise within promise constructor

const setTimeoutProm = (delay) => new Promise(res => setTimeout(() => res(delay),delay))
I want to do something like,
const asyncOpr = (delay) => {
return new Promise((resolve, reject) => {
//update delay for some reason.
const updatedDelay = delay * 2;
setTimeoutProm(updatedDelay).then(res => {
resolve(res);
}).catch(err => {})
})
}
asyncOpr(2000).then(() => alert("resolved")) //this works
This works as expected, but I am not sure if this is correct way of doing this or is there any better way of doing this ?
No, actually the way you do it is an antipattern.
You can just return a promise from the function:
const asyncOpr = (delay) => {
return setTimeoutProm(delay);
};
If needed, a Promise could also be returned from inside a .then:
doA()
.then(() => setTineoutProm(1000))
.then(() => doB());
Or it can also be awaited inside an async function:
async function asyncOpr(delay) {
//...
await setTimeoutProm(delay);
//...
}

Using a setTimeout in a async function [duplicate]

This question already has answers here:
Combination of async function + await + setTimeout
(17 answers)
Closed 7 months ago.
I have a async function that waits for an axios call to complete before proceeding. The problem is that I need to put a timeout on the axios call to half a second so that I don't hit the shopify API call limit.
async function processMatchingSchools(customer_metafield_url) {
for (const item of customer_metafield_url) {
await axios.get(item).then((res) => {
for (key in res.data.metafields) {
if (res.data.metafields[key].value === schoolName) {
id_for_each_student.push(shopifyAdmin + "/customers/" + res.data.metafields[key].owner_id + "/metafields.json")
}
}
})
}
console.log("Customer metafields to search", id_for_each_student)
processOwnerIds(id_for_each_student)
}
when I try putting a setTimeout, it calls the setTimeout and moves on before completing the axios calls.
async function processMatchingSchools(customer_metafield_url) {
for (const item of customer_metafield_url) {
await setTimeout(function(item) {
axios.get(item).then((res) => {
for (key in res.data.metafields) {
if (res.data.metafields[key].value === schoolName) {
id_for_each_student.push(shopifyAdmin + "/customers/" + res.data.metafields[key].owner_id + "/metafields.json")
}
}
})
}, 500)
}
console.log("Customer metafields to search", id_for_each_student)
processOwnerIds(id_for_each_student)
}
Any help?
await only works on promises.
You need to wrap setTimeout in a promise:
const waitFor = delay => new Promise(resolve => setTimeout(resolve, delay));
await waitFor(500);
setTimeout() doesn't return a Promise, but you can wrap it in one like this. I also cleaned up the rest of your code a little.
async function processMatchingSchools(customer_metafield_url) {
for (const item of customer_metafield_url) {
await new Promise(resolve => {
setTimeout(resolve, 500)
})
await axios.get(item).then((res) => {
Object.values(res.data.metafields).filter(
({ value }) => value === schoolName
).forEach(({ owner_id }) => {
id_for_each_student.push(`${shopifyAdmin}/customers/${owner_id}/metafields.json`)
})
})
}
console.log("Customer metafields to search", id_for_each_student)
processOwnerIds(id_for_each_student)
}
setTimeout does not return a promise so cannot be awaited.
You could create your own promise-based setTimeout and use that.
const setTimeoutPromise = timeout => new Promise(resolve => {
setTimeout(resolve, timeout);
});
await setTimeoutPromise(500);
Create a sleep function that returns a promise that you can use, like so:
const sleep = (milliseconds=500) => new Promise(resolve => setTimeout(resolve, milliseconds))
And to use it in an async function:
(async () => {
console.log("function invoked...")
await sleep(500)
console.log("I got here about 500 milliseconds later")
})()
You need to to create new promise for example like that
function delay(ms){
return new Promise(resolve => setTimeout(resolve, ms))
}
And then use it in your code before calling API
...
await delay(500)
await axios.get(item).then((res) => {
...
I created setTimeout2 function that works the same just as a promise:
const setTimeout2 = (callback, ms) => {
return new Promise(resolve => setTimeout(() => {
callback();
resolve();
}, ms));
}
So, altogether (noticed the setTimeout2 change):
async function processMatchingSchools(customer_metafield_url) {
for (const item of customer_metafield_url) {
await setTimeout2(function(item) {
axios.get(item).then((res) => {
for (key in res.data.metafields) {
if (res.data.metafields[key].value === schoolName) {
id_for_each_student.push(shopifyAdmin + "/customers/" + res.data.metafields[key].owner_id + "/metafields.json")
}
}
})
}, 500)
}
console.log("Customer metafields to search", id_for_each_student)
processOwnerIds(id_for_each_student)
}

Categories

Resources