taesu
taesu

Reputation: 4570

Promise infinite callback

const foo = () => {
  console.log('ok')
  return Promise.resolve(1);
}

let bar = foo(); // line 1
bar.then(() => { // line 2
  bar = foo(); // line 3
})

Wondering why line 3 doesn't refresh line 2
causing infinite
1. promise resolve
2. re-instantiating bar back to 1.

If you'd actually want it to infinitely cycle as stated above, how would you change this code without writing a callback hell?

Upvotes: 1

Views: 132

Answers (3)

antonku
antonku

Reputation: 7665

You can use a recursive function that and resolves a promise in every iteration

const foo = () => new Promise(resolve => {
  setTimeout(() => {
    console.log('ok');
    resolve()
  }, 1000)
})

const loop = (task) => {
  task().then(() => {
    loop(task)
  })
}

loop(foo)

Upvotes: 0

weegee
weegee

Reputation: 3399

const foo = () => {
  console.log('ok')
  return Promise.resolve(1);
}

let bar = foo(); // line 1
bar.then((val) => { // line 2
   bar = foo() // line 3
})

First, we execute foo() here

let bar = foo(); // console.log('ok')

Then you do

bar.then((val) => { // after it
   bar = foo() // you again run this and get console.log('ok')
})

Then what? No one runs it again.

Want an infinite loop?

const foo = () => {
  console.log('ok')
  return Promise.resolve(1);
}

Promise.resolve().then(function resolver() {
    return foo()
    .then(() => console.log("ok"))
    .then(resolver);
})

Upvotes: 0

trincot
trincot

Reputation: 350137

Here is how you can loop endlessly. To not block the browser completely, I have added a setTimeout so the promise only resolves after about half a second:

const foo = () => {
  console.log('ok');
  // Lets give the browser some air to breathe...
  return new Promise(resolve => 
      setTimeout(() => resolve(1), 500)
  );
}

const loop = async () => {
    while (true) await foo();
};

loop();

Without async await syntax:

const foo = () => {
  console.log('ok');
  // Lets give the browser some air to breathe...
  return new Promise(resolve => 
      setTimeout(() => resolve(1), 500)
  );
}

const loop = () => {
    foo().then(loop);
};

loop();

Upvotes: 1

Related Questions