Silver
Silver

Reputation: 5091

Dynamically define function in Bluebird promise

I have what I thought was a simple problem - but I simply can't solve it. I have a API that I'm using that returns a function for me to call when all my code is complete. I had thought that I could just put the function in a finally call - but it seems I can't redefine functions during a promise chain.

A simple example:

let a= function() {console.log("at the start");};
BbPromise.resolve("Executing")
    .tap(console.log)
    .then(function() {a = function() {console.log("at the end");}})
    .finally(a); 

How would I go about getting "At the end" to print out, at the end? This example will always print "At the start". If I use strings instead of functions, it works as expected.

Upvotes: 0

Views: 75

Answers (1)

Bergi
Bergi

Reputation: 664797

You're passing a to the finally call before you overwrite it from the asynchronous callback - a classic.

You just have to dereference a in the finally callback:

.finally(function() { a(); })

Of course, notice that redefining a function is weird and there is probably a better a approach to solve your actual problem. If you expect to get a promise for a function, you shouldn't make a global variable for the function but rather do .then(fn => fn()).

Upvotes: 2

Related Questions