简体   繁体   中英

returned results from promise.all() does not capture scoped variable

I am having issue with capturing each id from queryArray and storing it with the return promise results.

getSavedQueries: function(req, res) {
    SPromise.then(function(client) {
      const SavedQuery = client.Reports;
      var queryArray = req.query.queryArray; // ['123', '234', '456']
      var payloadObj = {};
      var actions = lo.map(queryArray, function(id) {
        var queryID = Number(id);
        *payloadObj['ID'] = queryID;* <--- not sure where to put this
        return SavedQuery.findOne(queryID).then(function(result){
          payloadObj['query'] = result;
          return payloadObj
        });
      });
      return Promise.all(actions);
    }).then(function(result){
      return res.json(result)
    });
  }

my res.json(result) returns with the last item on the array for all three objects:

[ {ID: 456, query: ...}, 
  {ID: 456, query: ...}, 
  {ID: 456, query: ...}]

Instead of :

  [ {ID: 123, query: ...}, 
    {ID: 234, query: ...}, 
    {ID: 456, query: ...}]

The problem is that payloadObj is defined outside of the map callback. Because of this, the same object is being mutated during the map callback and returned from the then method called on the promise created in the map callback, so that the array passed to Promise.all contains 3 promises which will all resolve to the same object , whose ID property will be the last ID in the array (since this map callback is called last) and whose query property will be the result of the last request that succeeds (probably, but not necessarily, the last request).

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