我希望以下循环遍历matchCenterItem
的每个实例,但由于某种原因,它仅使用第一个实例的属性ping ebay。然而,控制台在函数末尾记录,遍历所有实例并记录它们各自的属性。
Parse.Cloud.define("MatchCenterTest", function(request, response) {
var matchCenterItem = Parse.Object.extend("matchCenterItem");
var query = new Parse.Query(matchCenterItem);
var promises = [];
query.limit(10);
query.find().then(function(results) {
for (i=0; i<results.length; i++) {
url = 'http://svcs.ebay.com/services/search/FindingService/v1';
promises.push(Parse.Cloud.httpRequest({
url: url,
params: {
'OPERATION-NAME' : 'findItemsByKeywords',
'SERVICE-VERSION' : '1.12.0',
'SECURITY-APPNAME' : '*App ID goes here*',
'GLOBAL-ID' : 'EBAY-US',
'RESPONSE-DATA-FORMAT' : 'JSON',
'REST-PAYLOAD&sortOrder' : 'BestMatch',
'paginationInput.entriesPerPage' : '3',
'outputSelector=AspectHistogram&itemFilter(0).name=Condition&itemFilter(0).value(0)' : results[i].get('itemCondition'),
'itemFilter(1).name=MaxPrice&itemFilter(1).value' : results[i].get('maxPrice'),
'itemFilter(1).paramName=Currency&itemFilter(1).paramValue' : 'USD',
'itemFilter(2).name=MinPrice&itemFilter(2).value' : results[i].get('minPrice'),
'itemFilter(2).paramName=Currency&itemFilter(2).paramValue' : 'USD',
//'itemFilter(3).name=LocatedIn&itemFilter(3).Value' : request.params.itemLocation,
'itemFilter(3).name=ListingType&itemFilter(3).value' : 'FixedPrice',
'keywords' : results[i].get('searchTerm'),
},
// success: function (httpResponse) {
// // parses results
// var httpresponse = JSON.parse(httpResponse.text);
// response.success(httpresponse);
// console.log('MatchCenter Pinged eBay dude!');
// },
// error: function (httpResponse) {
// console.log('error!!!');
// response.error('Request failed with response code ' + httpResponse.status);
// }
}));
console.log(results[i].get('itemCondition'));
console.log(results[i].get('maxPrice'));
console.log(results[i].get('minPrice'));
console.log(results[i].get('searchTerm'));
}
});
Parse.Promise.when(promises).then(function(results) {
var httpresponse = JSON.parse(httpResponse.text);
response.success(httpresponse);
}, function(err) {
console.log('error!!!');
});
});
答案 0 :(得分:3)
这是因为http请求是异步的,并且您在第一个(和所有)请求的完成处理程序中调用response.success。使用promise语法,只有在完成后才能完成。简化概念:
var promises = [];
for (...) {
promises.push(Parse.Cloud.httpRequest({...})); // no success/error params
}
Parse.Promise.when(promises).then(function(results) {
response.success(...);
}, function(err) {
});