2

How can i get via promise the data from a callback function? Is that possible?

Here is my Code:

var bricklets = [];
var ipcon = new Tinkerforge.IPConnection();
pcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE, function(uid, connectedUid, position, hardwareVersion, firmwareVersion, deviceIdentifier, enumerationType) {
    if (enumerationType === Tinkerforge.IPConnection.ENUMERATION_TYPE_DISCONNECTED) {
        console.log('');
        return;
    }
    bricklets.push(new Bricklet(uid, deviceIdentifier, connectedUid));
});

I know that this solution will not work, but i dont have any idea to get the data outside the function via promise.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
mk2015
  • 205
  • 2
  • 14

1 Answers1

2

Since your callback is called back multiple times, it is a bit more complicated than just promisifying your API by passing resolve/reject as callbacks to your method.

You'd call resolve with the array of results once the last call was made:

var promise = new Promise(function(resolve, reject) {
    var bricklets = [];
    var ipcon = new Tinkerforge.IPConnection();
    pcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE, function(uid, connectedUid, position, hardwareVersion, firmwareVersion, deviceIdentifier, enumerationType) {
        if (enumerationType === Tinkerforge.IPConnection.ENUMERATION_TYPE_DISCONNECTED) {
            return resolve(bricklets); // when done
//                 ^^^^^^^
        } // else if some error happened
            // return reject(err);
        bricklets.push(new Bricklet(uid, deviceIdentifier, connectedUid));
    });
});

Now, you don't really get your data "out of the callback" in the sense that they would be synchronously returned (promises are still async callbacks), but you get a promise for the data that is much easier to work with than using callbacks.

You might consume it like

promise.then(function(bricklets) {
    console.log(bricklets);
    … // do more
}); // returns a new promise for the result of "do more"
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375