Reputation: 35
Hi all, I got a problem when using Parse.Promise.when in Parse Cloud Code.
In my Parse Cloud Code, I want to update the arrival time of a list of flight records which already existed in my database.
What I'm doing is pass a flight_list
which is the latest flight record and iterate each record, find the responding record using Parse.Query.first
and push the promises to a list and return the list to the next promise chain then
function.
I expect I can get a list of result, but I only get the first query result and have no idea why. The following is my code:
// Here we start a function
Parse.Cloud.httpRequest(
// Some HTTP request
).then(function(httpResponse) {
// Some pre-processing...
// flight_list is obtained here. It is a list of javascript object
// Here start the related code
var FlightInfo = Parse.Object.extend('FlightInfo'); // Flight object
var promises = []; // Promise list for next promise chain input
// Iterate each element in flight_list
_.each(flight_list, function(flight) {
var query = new Parse.Query(FlightInfo);
query.equalTo('flight_date' , flight_date);
query.equalTo('air_carrier' , flight.air_carrier);
query.equalTo('flight_no' , flight.flight_no);
query.equalTo('terminal' , flight.terminal);
query.equalTo('origin' , flight.origin);
// Push query.first promises to a list
promises.push(query.first());
});
// Return promise list and flight_list for next "then" function use
return Parse.Promise.when(promises, flight_list);
}).then(function(query_result) {
// 1. query_result should be the promises list in the previous then function
// 2. flight_list will be accessed using argument keyword
// !! Only got first element from promises list in previous function
console.log('query_result:');
console.log(query_result);
// No problem for flight_list.
for (var i = 0; i < arguments.length; i += 1) {
console.log(i + ':' + JSON.stringify(arguments[i]));
}
});
As the code above, I expect query_result
is a list of javascript object (flight information) like: [{object1}, {object2}, {object3}, ...]
But query_result
is an object: {object1}
. It is even not one object in a list like [{object1}]
.
Did I miss anything in my code? How should I modify my code to get the correct return value?
Upvotes: 2
Views: 1125
Reputation: 784
You're getting confused with the API params. Parse.Promise.when has 2 signatures -
Since you're sending the 2nd param, which isn't a promise, you're unknowingly using the 1st when. Hence the response only has 1 element corresponding to the first promise.
Solution is
// Where mFlightList is a global variable
mFlightList = flight_list;
return Parse.Promise.when(promises);
}).then(function() {
// arguments contains the actual result of the promises passed in 'when'
for (var i = 0; i < arguments.length; i += 1) {
console.log(i + ':' + JSON.stringify(arguments[i]));
}
});
Upvotes: 1