最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Promises: How to resolve an unknown amount of promises - Stack Overflow

programmeradmin7浏览0评论

I have a function that takes in an unknown amount of building id's in an array i.e [4,5] and then calls a function which returns it's name and description. I don't know how to approach this given that it is an unknown amount. I tried creating a for loop but that led nowhere and I'm pletely lost. What you see below is me sending an entire array to a function, but I want to loop through each element and call the function individually

Edit: Thank you everybody for the kind replies. You have been very helpful and supportive

function getBuilding(buildingId){
      return new Promise(function(resolve,reject){
          Building.getBuilding(buildingId).then((buildingInfo)=>{
              resolve(buildingInfo);
          }); 
      })
}

I have a function that takes in an unknown amount of building id's in an array i.e [4,5] and then calls a function which returns it's name and description. I don't know how to approach this given that it is an unknown amount. I tried creating a for loop but that led nowhere and I'm pletely lost. What you see below is me sending an entire array to a function, but I want to loop through each element and call the function individually

Edit: Thank you everybody for the kind replies. You have been very helpful and supportive

function getBuilding(buildingId){
      return new Promise(function(resolve,reject){
          Building.getBuilding(buildingId).then((buildingInfo)=>{
              resolve(buildingInfo);
          }); 
      })
}
Share Improve this question edited May 1, 2019 at 15:23 nodeboi asked May 1, 2019 at 15:08 nodeboinodeboi 451 silver badge10 bronze badges 4
  • 4 Promise.all? – p.s.w.g Commented May 1, 2019 at 15:10
  • 1 The whole function in your question is equivalent to function getBuilding(buildingId){ return Building.getBuilding(buildingId); }. There is no need to use a Promise constructor there. – Paul Commented May 1, 2019 at 15:11
  • But I call the function an unknown amount of times – nodeboi Commented May 1, 2019 at 15:12
  • 1 @nodeboi Promise.all( buildingIdsArray.map( getBuilding ) ).then( buildingInfoArray => { ... } ); – Paul Commented May 1, 2019 at 15:13
Add a ment  | 

4 Answers 4

Reset to default 6

You want to use Promise.all, the promise of all will resolve once all the items in the array have also resolved. This then will return a promise with an array of the results where the first item is the first building id result, the second is the second id, and so on.

function getBuilding(ids) {
  let promises = []
  // We will assume `getInfo()` returns a promise that resolves the buildings info
  ids.forEach(id => promises.push(getInfo(id)))
  return Promise.all(promises)
}

function getInfo(id) {
  // Resolves the info after a random amount of time to simulate
  // something that may take some time to execute.
  return new Promise(resolve => setTimeout(() => resolve({id}), Math.floor(Math.random() * 5000)))
}

console.log('Just a moment, calculating data...')
getBuilding([3, 5, 7, 9]).then(results => {
  console.log('building id', results[0].id) // buildingId = 3
  console.log('building id', results[1].id) // buildingId = 5
  console.log('building id', results[2].id) // buildingId = 7
  console.log('building id', results[3].id) // buildingId = 9
})

The Promise.all() method takes an array of promises and waits till they all resolve.

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});

Note that if any one of the promises fail Promise.all() will fail.

You can use Promise.all which takes and iterable which in this case can be an array.

Like:

function caller( ...promises ) {
    Promise.all( promises ).then( function( value ) {
      console.log( 'all pleted' );
    });

}

Where promises is basically an array of arguments, take a look at:

  • https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Functions/arguments#Description

I think spread operator and Promise.all

function getInfos(...ids) {
  return Promise.all(ids.map(id => Building.getBuilding(id )));
}

//      can be any number of params
getInfos(id1, id2, id3).then(([info1, info2, info3]) => {
  // do stuff
});

I saw in an other ment buildingId is array, in that case:

const buildingId = [1, 2, 3];
getInfos(...buildingId).then(([info1, info2, info3]) => {
  // do stuff
});

or simplified

function getInfos(ids) {
  return Promise.all(ids.map(id => Building.getBuilding(id )));
}

const buildingId = [1, 2, 3];
getInfos(buildingId).then(([info1, info2, info3]) => {
  // do stuff
});
发布评论

评论列表(0)

  1. 暂无评论