简体   繁体   中英

Promise.All returning empty

I have few api call requests which i am trying to create promises and then execute all using Promise.all but, its giving empty value instead of array. Below is my code.

function getUser(arrUser) {
  var student = [];
  return new Promise((resolve, reject) => {
    if (arrUser.length > 0) {
      var promises = arrUseridRequest.map(userRequeset => {
        return getRequest(userRequeset).then(result => {
          student.push(JSON.parse(result.body).result[0].Name);
          console.log(student); //This is giving right details.
        }).catch(error => {
          reject(error);
        });
      });

      Promise.all(promises).then(StuName => {
        resolve(StuName.join());
      })
    }
  });
}

and this is how i am trying to get the values at once:

getUser('123').then(student => {
  console.log(Student) //Coming as empty
});

getRequest is my api call nodeJs request module. What's wrong in my code?

All your promises fulfill with the value undefined since you're just logging the student names, but not return ing them from the then callback. As you seem to be doing only a single request, the array will be [undefined] , which is joined into the empty string.

Also avoid the Promise constructor antipattern :

function getUsers(arrUser) {
  const promises = arrUser.map(userId => {
    return getRequest(userId).then(result => {
      const students = JSON.parse(result.body).result;
      return students[0].Name;
    });
  });
  return Promise.all(promises);
}
getUsers(['123']).then(studentNames => {
  console.log(studentNames);
  console.log(studentNames.join());
}).catch(console.error);

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