Promise.all返回一个undefined数组

时间:2016-01-15 14:23:42

标签: javascript node.js for-loop asynchronous promise

我遇到函数返回未定义数组的问题。

这是代码:

classMethods.getQueries = function(models, dbId, dateStart, dateEnd) {
  return new Promise(function(resolve, reject) {

    /* Fetch database .... */
    .then(extractQueries, reject)
    .then(sortQueries, reject)
    .then(onlyTen, reject)
    .then(addText, reject)
    .then(function(queries) {
      console.log('getQueries finished', queries) ;  //array of 10 undefined! 
      resolve(queries);
    }, reject);

    /* Functions here .... */

  });
};

在addText函数之前一切正常:

function addText(queries) {
  return Promise.all(queries.map(function(query) {

    models.queries.findById(query.queryId, { raw: true, attributes: ['query'] })
    .then(function(queryFetched) {
      query.text = queryFetched.query;
      console.log(query);
      return Promise.resolve(query);
    }, function(error) {
       return Promise.reject(error);
    });

  }));
};

这给了我一个像:

getQueries finished [undedfined 10x]

10x  
[query database]
{queryId: ***, text: ********}

我不知道为什么在循环未完成时返回promise。

感谢您的帮助。

2 个答案:

答案 0 :(得分:15)

这是因为您在地图的回调中没有回复任何承诺:

function addText(queries) {
  return Promise.all(queries.map(function(query) {
    // add return here or the map returns an array of undefined
    return models.queries
      .findById(query.queryId, {
        raw: true,
        attributes: ['query']
      })
      .then(function(queryFetched) {
        query.text = queryFetched.query;
        console.log(query);
        return Promise.resolve(query);
      }, function(error) {
        return Promise.reject(error);
      });

  }));
};

答案 1 :(得分:0)

所以这里解决了我的问题:

function addText(queries) {
  return Promise.all(queries.map(function(query) {
    return new Promise(function(resolve, reject) {

      models.queries.findById(query.queryId, { raw: true, attributes: ['query'] })
      .then(function(queryFetched) {
         query.text = queryFetched.query;
         resolve(query);
      }, reject);

    });
  }));
};