简体   繁体   中英

Parse Promise 'when' returns undefined (Javascript)

I'm trying to follow the 'when' example on Parse JavaScript SDK: Parse.Promise with the following code:

GetFromDB2 = function(id) {
    var DB2 = Parse.Object.extend("DB2");
    var q = new Parse.Query(DB2);
    q.get(id, {
        success: function(res) {
            return Parse.Promise.as(10);
        },
        error: function(res, err) {
            console.log( err);
        }
    });
}

GetData = function() {
    var DB1 = Parse.Object.extend("DB1");
    var query = new Parse.Query(DB1);
    query.equalTo("param", "close");

    query.find().then(function(results) {
        var promises = [];
        _.each(results, function(res) {
            promises.push(GetFromDB2(res.get("user")));
        });

        Parse.Promise.when(promises).then(function() {
            console.log(arguments); // expect: [10, 10, ...]
        })
    }); 
};

The length of the array arguments is correct but not sure why its values are undefined.

As written, GetFromDB2() returns undefined . To deliver a value, it must return either a value or a promise.

At its simplest, to deliver 10 , you could write :

function GetFromDB2(id) {
    return 10;
}

But to be asynchronous, and still deliver 10 , you need to return a promise that will resolve to 10 :

function GetFromDB2(id) {
    return Parse.Promise.as(10);
}

Or the .get(id) query you really want :

function GetFromDB2(id) {
    var DB2 = Parse.Object.extend('DB2');
    var q = new Parse.Query(DB2);
    return q.get(id).then(function(res) {
        return 10;
    });
    //omit `.then(...)` entirely to deliver `res`
}

Now GetData() can be written as follows :

function GetData() {
    var DB1 = Parse.Object.extend('DB1');
    var query = new Parse.Query(DB1);
    query.equalTo('param', 'close');
    return query.find().then(function(results) {
        var promises = _.map(results, function(res) {
            return GetFromDB2(res.get('user'));
        });
        Parse.Promise.when(promises).then(function() {
            console.log(arguments); // expect: [10, 10, ...]
        }, function(err) {
            console.log(err);
            return err;
        });
    }); 
};

Notes:

  • promises = _.map(...) is more elegant than _.each(...) plus `promises.push(...).
  • moving the error handler into GetData() allows a greater range of possible errors to be handled, eg an error arising from query.find() .
  • By returning a promise, GetData()'s caller is also informed of the eventual asynchronous outcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM