user10965730
user10965730

Reputation: 97

how to re-run a javascript promise with `then` re-call?

I want to re-run a promise and this promise's all own thenable handler. That means, re-run a promise, and run all its .then() or .finally().

const promise = Promise.resolve(1)
promise.then(value => {
  console.log(value) // 1
  return value + 1
})

// or, has another `then`, or `.finally()`

promise.reRun() // how to Implement this method
// call `reRun()`, then `console.log(value)` will re-run too.

Upvotes: 1

Views: 264

Answers (2)

Bergi
Bergi

Reputation: 665276

You cannot. A promise is not "callable" or "executable". Make a function that returns a promise instead, that you can call as often as you want.

Upvotes: 1

Justinas
Justinas

Reputation: 43519

Move code to function. In .then re-call same function.

function run() {
    Promise
        .resolve(1)
        .then(value => {
            console.log(value) // 1

            run(); //Note that this will create infinite loop

            return value + 1;
        })
}

run();

Upvotes: 0

Related Questions