MayNotBe MayNotBe - 1 year ago 181
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);
}).then(function(data) {

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

Any help would be appreciated.

Answer Source

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); }
    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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download