创建一个存储已解决的Promises数组的变量?

时间:2017-12-21 18:48:25

标签: javascript express spotify

我觉得我在这里挖洞。我有一系列艺术家的名字,并使用Spotify的API我想抓住每个艺术家的顶部曲目并将其传递到我的视图页面。因此,使用Spotify的API,我可以搜索艺术家的名字,但为了抓住他们的每个顶级曲目,我也需要他们的ID。我写了这个:

      PromiseArr = [];
      // Search with Spotify's API for each artist from the list of concerts retrieved
      for (var i = 0; i < concerts.length; i++) {

     // Create an array of unresloved promises and resolve all of them afterwards with Promise.all 

        PromiseArr.push(spotifyApi.searchArtists(concerts[i].performance[0].displayName));
      }

      let artists = [];
      artists = new Promise((resolve, reject) => {
        Promise.all(PromiseArr)
          .then(values => {

            // Retrieve the Artist ID in order to make calls for specific track's
            const artistIds = values.map(element => {
              if (element.body.artists.items[0]) {
                return element.body.artists.items[0].id;
              }
            });
            resolve(artistIds);
          })
          .catch(err => reject(err));
      });
      artists.then(value => res.json(value.filter(element => element != null)));

所以这给了我一系列所有艺术家代码:

[
  "391oLRVmoTkumiN79HkTWu",
  "066X20Nz7iquqkkCW6Jxy6",
  "3ur7kjN4pd94zjUxrFSMDj",
  "26AHtbjWKiwYzsoGoUZq53",
  "3P33qFNGBVXl86yQYWspFj",
  "3bFSIkxpW9NvKT1wzo9tgx",
  "4MOSNls51nJPFORKok60vV",
  "50JJSqHUf2RQ9xsHs0KMHg",
  "6reL7Hq6obyCxSqurc8i1D",
  "0I7U5I66P88nCaVVPkIz6x",
]

从那里,我将能够遍历这些值并进行API调用以检索每位艺术家的顶部曲目。但是,我觉得我正在做的事情非常多余。而且我似乎无法将艺术家的ID存储到变量中并循环遍历这些变量。即

const IDs = artists.then(value => res.json(value.filter(element => element != null)));

IDs将为空。我怎么能继续谈论这个?

1 个答案:

答案 0 :(得分:1)

您可以使用Array.map将该艺术家代码数组转换为承诺数组。然后使用Promise.all检测数组中所有promises的实现时间。

例如。

获取艺术家代码数组:

var array = [
  "391oLRVmoTkumiN79HkTWu",
  "066X20Nz7iquqkkCW6Jxy6",
  "3ur7kjN4pd94zjUxrFSMDj",
  "26AHtbjWKiwYzsoGoUZq53",
  "3P33qFNGBVXl86yQYWspFj",
  "3bFSIkxpW9NvKT1wzo9tgx",
  "4MOSNls51nJPFORKok60vV",
  "50JJSqHUf2RQ9xsHs0KMHg",
  "6reL7Hq6obyCxSqurc8i1D",
  "0I7U5I66P88nCaVVPkIz6x",
];

根据第一个数组中的代码,使用Array.map创建一个新的promises数组(而不是字符串)。

var promiseArray = array.map(function(item) {
    return new Promise(function(resolve, reject) {
        //do API call here
        //item will be the string of the artist code
        //call the resolve function when complete with the API call
    });
});

然后,您可以使用Promise.all来检测promiseArray中所有承诺何时解决或第一个承诺失败(如果失败)。

Promise.all(promiseArray).then(function(results) {
    //do stuff here
}).catch(function(error) {
    //handle error here
});