为承诺保存更改变量



我正在使用我的数据库访问承诺(elasticsearchjs,它使用蓝鸟)。

对于我的列表中的每个ID,我开始一个新的查询。现在我想知道查询失败时元素的ID。

var idList = ['id1', 'id2', 'id3', '...'];
var promises = [];
for (var i = 0; i < size; i++) {
  // dbQueryFunction returns a promise object
  promises.push(dbQueryFunction(idList[i])
    .then(function(data) {
        // Do stuff...
    })
    .error(function(errorMessage) {
      console.log('[ERROR] id: ' + id); //<== Print ID here
    })
  );
}
// Wait for all promises to be resolved
Promise.all(promises)
  .then(function() {
    console.log('Everything is done!');
  });

我如何在我的承诺中保存额外的信息?我尝试使用Promise.bind(),但无法使其工作。

编辑:

澄清一下"size"变量:在这段代码中,我想要的是前n个元素的结果。size等于或小于数组大小

解决方案是:

var promises = idList.map(function(id){
    return dbQueryFunction(id)
    .then(function(data) {
        // Do stuff...
    })
    .error(function(errorMessage) {
      console.log('[ERROR] id: ' + id); 
    });
});

(如果size变量不能保存数组的大小,则使用idList.slice(0,size)代替idList)。

注意bind:它可以,也许,在这里可用(添加.bind(idList[i]),然后记录this),但问题是你不创建(因此不拥有)承诺对象。如果查询库依赖于特定的上下文怎么办?

var idList = ['id1', 'id2', 'id3', '...'];
var promises = [];
 // Could you do this?
   promises.push(dbQueryFunction(idList[i])
     .then(function(data) {
       // Do stuff...
       idList.deleteID(idList[(promises.length - 1) || 0]);
       // Or something to remove the successful ids from the list
       // leaving you with the idList of the unsuccessful ids
     })
     .error(function(errorMessage) {
        console.log('[ERROR] id: ' + idList[0]); //<== Print ID here
     })
  );
Array.prototype.deleteID = function(array,id){
   array.forEach(function(el,indx,arr){
      if(el == id){
         arr.splice(indx,1);
      }
   });
};

最新更新