0

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.

Silver
  • 4,911
  • 3
  • 15
  • 16
  • What exactly is that API doing? Can you link its docs, or post your actual code? – Bergi Feb 23 '16 at 22:38
  • The API is actually returning a function that allows me to delete a message retrieved from a queue. The library is sqs-consumer - which I have promisifed, but I still need to deal with an onDone callback after checking the message – Silver Feb 23 '16 at 22:55
  • If you mean the `create` function, I don't think you can promisify that. `handleMessage` is called multiple times, not only once like a promise that resolves. You should just be doing `function handleMessage(msg, done) { doWhateverYouNeedToDoThatReturnsAPromise(msg).asCallback(done); }`. The only thing that would make sense is to decorate `create` so that `handleMessage` can be a promise-returning function instead of a callback-receiving one. – Bergi Feb 23 '16 at 23:40

1 Answers1

2

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()).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Perfect! Unfortunately the library I'm using doesn't return a promise, and I don't get visibility of function it returns until after events have fired - via a callback. Any better solution would be gladly welcomed though! – Silver Feb 24 '16 at 01:59
  • 1
    @Silver: Please show us the exact code you're using for sqs-consumer, and we may be able to help you improve it. You should ask a new question for that, possible at [codereview.SE]. – Bergi Feb 24 '16 at 02:40