2

Is there a way to convert a Javascript call with callback which can be called multiple times into a promise?

Say,

scan(function(result) {
  // this is actually a Bluetooth device scan (Cordova), and 
  // will return something when a device is found.
  // So this can be called more than once.
});

And wrap that into a promise?

function scanP {
  return new Promise(function(resolve, reject) {
    scan(function (result) {
     resolve(result); // attempt to call repeatedly, but doesn't work.
    });
  });
}

scanP(function(result) {
   // check if this device is what we want.
})
.catch(function(err) {
  // handle error
});

I also need this pattern to subscribe to data from a Bluetooth device. Is promise not suitable for this task?

EDIT: I'm using Bluebird.

3
  • 2
    attempt to call repeatedly - a Promise can only be fulfilled once (be it a resolve or a reject) - once it is fulfilled, it's value can not change Commented Aug 10, 2015 at 9:14
  • 4
    No, a promise is singular, use an observable or an event emitter Commented Aug 10, 2015 at 9:15
  • A Promise can indeed only be resolved once but he is creating a new Promise every time scanP is called which in turn, can be resolved. If I've understood correctly, what you've written is almost there except you want scanP().then(function(result) {})... here's an example: jsbin.com/johagevofe/1/edit?js,console Commented Aug 11, 2015 at 14:25

1 Answer 1

2

Promise is resolved only once. If want to resolve it multiple times then you want something other than promise.

You may want custom events (in browser), Node's EventEmitter or Stream (inherits EventEmitter, has .pipe, optional buffering). If all you want is a callback chaining solution then it seems not hard to write your own.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.