在promise中将变量设置为Parse Query的result只显示响应中的第一项



My Parse Cloud Code查询所有用户的matchCenterItem实例,并使用这些实例的结果属性作为promise函数的参数。

我想要的是承诺函数返回的每个"前3名"JSON都有自己各自的searchTerm值,正如我构建响应的方式所示。我尝试过这样做,如下图所示,但这导致每个"Top 3"显示相同的"搜索项"值,而不是迭代并为每个matchCenterItem实例显示不同的"搜索项"。

我认为这可能是因为我在承诺之外定义了searchTerm变量,但我不知道如何在承诺内定义,因为它是一个httpRequest。

Parse.Cloud.define("MatchCenter", function(request, response) {
    //defines which parse class to iterate through
    var matchCenterItem = Parse.Object.extend("matchCenterItem");
    var query = new Parse.Query(matchCenterItem);
    var promises = [];
    //setting the limit of items at 10 for now
    query.limit(10);
    query.find().then(function(results) {
      for (i=0; i<results.length; i++) {
        var searchTerm = results[i].get('searchTerm');
        console.log(searchTerm);
        url = 'http://svcs.ebay.com/services/search/FindingService/v1';
        //push function containing criteria for every matchCenterItem into promises array
        promises.push((function() {
          var httpRequestPromise = 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'),
            }
          });
          return httpRequestPromise
        })());
      }

      //when finished pushing all the httpRequest functions into promise array, do the following  
      Parse.Promise.when(promises).then(function(results){
        //console.log(arguments);
        var eBayResults = [];
        for (var i = 0; i < arguments.length; i++) {
          var httpResponse = arguments[i];
          var top3 = collectEbayResults(httpResponse.text)
          eBayResults.push(top3);
        };
        function collectEbayResults (eBayResponseText){
          var ebayResponse = JSON.parse(eBayResponseText)
          var matchCenterItems = [];
              //Parses through ebay's response, pushes each individual item and its properties into an array  
              ebayResponse.findItemsByKeywordsResponse.forEach(function(itemByKeywordsResponse) {
                  itemByKeywordsResponse.searchResult.forEach(function(result) {
                    result.item.forEach(function(item) {
                      matchCenterItems.push(item);
                    });
                  });
              });
              var top3Titles = [];
              var top3Prices = [];
              var top3ImgURLS = [];
              var top3ItemURLS = [];
              //where the title, price, and img url are sent over to the app
              matchCenterItems.forEach(function(item) {
                var title = item.title[0];
                var price = item.sellingStatus[0].convertedCurrentPrice[0].__value__;
                var imgURL = item.galleryURL[0];
                var itemURL = item.viewItemURL[0];
                top3Titles.push(title);
                top3Prices.push(price);
                top3ImgURLS.push(imgURL);
                top3ItemURLS.push(itemURL);
              });

              var top3 = 
              {
                "Top 3": 
                [
                    { 
                      "Title": top3Titles[0], 
                      "Price": top3Prices[0], 
                      "Image URL": top3ImgURLS[0],
                      "Item URL": top3ItemURLS[0]
                    },
                    { 
                      "Title": top3Titles[1], 
                      "Price": top3Prices[1], 
                      "Image URL": top3ImgURLS[1],
                      "Item URL": top3ItemURLS[1]
                    },
                    { 
                      "Title": top3Titles[2], 
                      "Price": top3Prices[2], 
                      "Image URL": top3ImgURLS[2],
                      "Item URL": top3ItemURLS[2]
                    },
                    {
                       "Search Term": searchTerm
                    }
                ]
              }
              return top3
        }
        response.success
        (
          eBayResults
        );
      }, function(err) {
          console.log('error!');
          response.error('DAMN IT MAN');
          });
    });
});

只需在外部作用域中创建一个搜索词数组,就像您创建承诺数组并填充它一样填充承诺,然后将正确的searchTerms项传递给collectEbayResults()函数:

// up top where you declare promises:
var promises = [];
var searchTerms = [];
// ... later in your loop where you populate promises:
var searchTerm = results[i].get('searchTerm');
// add it to the array just like you add the promises:
searchTerms.push(searchTerm);
// ... later in your loop to extract the promise results:
for (var i = 0; i < arguments.length; i++) {
  var httpResponse = arguments[i];
  // since they're in the same order, this is OK:
  var searchTerm = searchTerms[i];
  // pass it as a param:
  var top3 = collectEbayResults(httpResponse.text, searchTerm)
  eBayResults.push(top3);
};
// ... lastly change your method signature:
function collectEbayResults (eBayResponseText, searchTerm) {

结果是,当该函数中的代码使用searchTerm时,它将使用传入的与响应匹配的代码。

最新更新