Wednesday, June 5, 2024
129
rated 0 times [  132] [ 3]  / answers: 1 / hits: 10983  / 3 Years ago, sun, january 3, 2021, 12:00:00

I have a function to update an user with an api post request. The backend is not done yet. The function will thus always return an error. In order to test the loading and error states, I would like to temporarily add a fake delay before returning the result. How to do so? Here is the function:




const updateProfile = async (form) => {
try {
const res = await api.post(/update-profile, form);
return res;
} catch (err) {
throw new Error(error.unknown);
}
};




Writing this didn't work:




const updateProfile = async (form) => {
try {
let fakeCallDone = false
setTimeout(()=> fakeCallDone = true, 2000)
const res = await api.post(/update-profile, form);
fakeCallDone && res;
} catch (err) {
throw new Error(error.unknown);
}
};




More From » asynchronous

 Answers
3

You can create a simple sleep function.


const sleep = ms => new Promise(
resolve => setTimeout(resolve, ms));

And then use like


 await sleep(2000);

[#2028] Saturday, December 26, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emanir

Total Points: 151
Total Questions: 90
Total Answers: 105

Location: Suriname
Member since Sun, Jun 13, 2021
3 Years ago
emanir questions
Wed, Dec 23, 20, 00:00, 4 Years ago
Fri, Aug 7, 20, 00:00, 4 Years ago
Fri, Feb 1, 19, 00:00, 5 Years ago
;