mk2015
mk2015

Reputation: 203

Javascript Get Promise Result from Callback

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.

Upvotes: 2

Views: 782

Answers (1)

Bergi
Bergi

Reputation: 664207

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"

Upvotes: 2

Related Questions