Home > Software engineering >  resolve promise after setTimeout inside promise
resolve promise after setTimeout inside promise

Time:02-02

I would like to resolve my promise after my setTimeout will be finished. I have a few functions like step The main idea is to get step results sequentially. P.S. we can't mutate setTimeout.

function step (done) {
  return new Promise((resolve, reject) => {
    try {
      setTimeout(done, 5100, 'hello world')
      resolve()
    } catch (error) {
      reject()
    }
  })
}

CodePudding user response:

If you can't mutate the setTimeout remove it. Instead of putting the setTimeout in the step function create a new delay function that returns a promise. You can then use async/await to walk through the steps after certain delays.

function delay(time = 1000) {
  return new Promise(res => {
    setTimeout(() => res(), time); 
  });
}

function step(fn, n) {
  fn(`hello world ${n}`);
}

const fn = (str) => console.log(str);

async function main() {
  step(fn, 1);
  await delay(5000);
  step(fn, 2);
  await delay(3000);
  step(fn, 3);
}

main();

CodePudding user response:

If you can change the done function, you can do like below.

function step(done) {
    return new Promise((resolve, reject) => {
        try {
            immutableFunc(done(resolve));
        } catch (error) {
            reject(error);
        }
    });
}

function immutableFunc(done) {
    setTimeout(done, 1000, "hello world");
}

function done(resolve) {
    return arg => {
        console.log(arg);
        resolve();
    };
}

async function test() {
    await step(done);
    await step(done);
    await step(done);
}

test();

  •  Tags:  
  • Related