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.
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 changescanP().then(function(result) {})... here's an example: jsbin.com/johagevofe/1/edit?js,console