MayNotBe MayNotBe - 4 months ago 28
Node.js Question

How to wrap a callback function in a Parse.Promise

I have a function:

function foo(aString, function(err, callback) {
//does stuff
}


I need to call that function from the middle of a long series of Parse.Promises.

How can I wrap it in a Parse.Promise?

I've tried:

//...
return new Parse.Promise(function(resolve, reject) {
foo(thatString, function(err, data) {
if(err) return reject(err);
resolve(data);
});
});
}).then(function(data) {
//...


and other variations like
Parse.Promise.as()
instead of
new Parse.Promise()


Any help would be appreciated.

Answer

You're on the right track, but Parse's promise constructor doesn't take resolve / reject functions. Instead, have your wrapper build and return a promise without params, then invoke that promise's resolve() or reject() methods in the wrapped function's callback, like this:

var wrappedFoo = function(aString) {
    var promise = new Parse.Promise();
    foo(aString, function(err, data) {
        if (err) { promise.reject(err); }
        promise.resolve(data);
    });
    return promise;
};

Call it like this:

wrappedFoo("bar").then(function(data) {
    // data will be the data passed to the foo callback
}, function(err) {
    // likewise for err
});