Why doesn’t the add wait for the timeout promise to resolve?

Tags: , , ,



Trying to play with how promises and async code works by making a calculator that will give me the answer after the given ms.

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

const add = (number1, number2) => {
  return new Promise(resolve => {
    timeout(1000).then(resolve(number1 + number2));
  });
};

add(5,3).then(result => console.log(result))

Why isn’t the add function waiting for the timeout? It goes directly to resolve regardless of how many ms I pass in. Omitted reject to make it more clear.

Answer

You call resolve immediately:

const add = (number1, number2) => {
  return new Promise(resolve => {
    timeout(1000).then(() => {
      resolve(number1 + number2);
    });
  });
};

As timeout is a Promise you can remove your outer completely:

const add = (number1, number2) => {
  return timeout(1000).then(() => {
    return number1 + number2;
  });
};


Source: stackoverflow