简体   繁体   中英

Promise.all is returning an array of undefined and resolves before being done

I am having trouble with a function returning an Array of undefined .

Here is code:

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.
  });
};

Everything is fine until the addText function:

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);
      });
  }));
};

This is giving me an output like:

"getQueries finished" [ undefined ×10 ]

10×
[query database]
{ queryId: "…", text: "…" }

I have no idea why the promise is returned while the loop is not finished.

It's because you're not returning any promise in your map's callback:

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);
      });

  }));
};

So here the solution of my problem:

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);

    });
  }));
};

I was having the same problem, my Promise.all(list) , results in an array of undefined, I used the same approach of adding a return to my function.

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