首页 > 解决方案 > 如何从具有作为参数传递的本地值的函数返回新的承诺?

问题描述

我想返回 promise.all() 并在下面本地定义源变量,这样我就可以在调用 sourceRequest.then((sources)=>{//do something}) 时使用该承诺,这是我的代码:

var sourceRequest=(...countries)=>{
    var sources=[];
    var promisesCollection=[];
    for(var country of countries)
    {
      var promise=this._vm.$axios.get('/sources',{params:{ country,language:'en'}})
      .then(response=>{
        sources.push(response.data.sources);
      });
      promisesCollection.push(promise); 
    }

    Promise.all(promisesCollection).then(()=>{
      return new Promise((resolve)=>resolve(sources));
    })
  };
  sourceRequest('in').then((sources)=>console.log(sources));

问题是我在控制台中未定义 解决方法: 我有一个解决方法,但问题是我希望函数返回源而不是 api 请求响应:

//this works
  var sourceRequest=(...countries)=>{
    var promisesCollection=[];
    for(var country of countries)
    {
      var promise=this._vm.$axios.get('/sources',{params:{ country,language:'en'}})
      promisesCollection.push(promise); 
    }

    return Promise.all(promisesCollection);
  };

   sourceRequest('in').then((response)=>{console.log(response)});

标签: javascriptpromise

解决方案


然后,您只需要一个步骤,将响应列表替换为源列表。

const promisedSources = Promise.all(promisesCollection)
                          .then(responses => 
                              responses.map(response => response.data.sources)
                          );
return promisesSources;

推荐阅读