Strategies for Simulating a Delay in an API Call Function


Solution 1:

It is possible to generate a basic function for sleeping.

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

And then use like

 await sleep(2000);

Solution 2:

The problem is here:

setTimeout(()=> fakeCallDone = true, 2000)

After performing


, the execution process will proceed to the next lines of code.


const updateProfile = async (form) => {
  try {
   var res ="/update-profile", form); // this async code will move on `web api`. When it's done will move on to queue.
   await delay(2000); // You mock a delay here
   return await res; // Resolve value from `res` promise. 
  } catch (err) {
    throw new Error("error.unknown");

The delay() function appears in the method as follows:

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

Additional information is necessary to understand

event loop

in greater depth.

  1. How js works:

    call stack, web API, queue, event loop
  2. Asynchronous programming in the Javascript language.

Solution 3:

In the interim (while waiting for the backend to be prepared), a fresh promise can be submitted.

const updateProfile = async () => {
  try {
    // const res = await"/update-profile", form);
    // return res;
    return new Promise((res, rej) => {
     setTimeout(() => res('response'), 2000)
  } catch (err) {
    throw new Error("error.unknown");

Frequently Asked Questions