1

I have 3 promises and all have diffrent setimeouts when I am using async the first one is coming out on console after 4 second as expected.

But the second and third are coming just after that without time delays of 3s and 2s respectively.

What can I do here so that first comes at 4s, second 3s after the first and third 2s after the seconds.

Here is the js code

const ank = async() => {
  let p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("resolved first");
    }, 2000);
  })
  let p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("resolved second");
    }, 3000);
  })
  let p3 = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("resolved third");
    }, 4000);
  })
  console.log("p3 started");
  let a = await p3.then((value) => {
    console.log(value)
  }).catch((error) => {
    console.lo(error);
  });
  console.log("p3 ended\n\n");


  console.log("p2 started\n")
  let b = await p2.then((value) => {
    console.log(value);
  }).catch((error) => {
    console.log(error);
  });
  console.log("p2 ended\n\n\n");


  console.log("p1 started\n")
  let b1 = await p1.then((value) => {
    console.log(value);
  }).catch((error) => {
    console.log(error);
  });
  console.log("p1 ended");
}
ank();
connexo
  • 53,704
  • 14
  • 91
  • 128
Brisvera
  • 73
  • 8
  • 2
    All three timers are started immediately. `await` doesn't "activate" the promise. – VLAZ Oct 20 '22 at 07:01
  • Is it not implemeted properly. But the p3 is coming out first despite setimeout function. – Brisvera Oct 20 '22 at 07:02
  • 1
    That's how promises work - the constructor is called immediately. If you *don't* want this, then don't crate them immediately but when you want to await them `await functionThatReturnsPromise()`. The only thing `await` does is wait for the promise to resolve. But once a promise is created, there is *something* already working towards resolving it. Promises are just a notification mechanism for an async operation. – VLAZ Oct 20 '22 at 07:03

1 Answers1

0

A promise is eagerly resolved and all the setTimeout starts simultaneously. So your are seeing the results instantly after the first Promise resolve. If you wish to delay the result, execute them only after the previous promise is resolved

function p1() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("resolved first");
    }, 2000);
  })
}

function p2() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("resolved second");
    }, 3000);
  });
}

function p3() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("resolved third");
    }, 4000);
  });
}

const ank = async() => {
  for (let item of [p3, p2, p1]) {
    const z = await item();
    console.log(z)
  }
}
ank();
brk
  • 48,835
  • 10
  • 56
  • 78