从函数中返回Promise.all

时间:2017-03-02 03:08:13

标签: javascript promise

我试图用Promise.all返回一个promise,但由于某种原因,我的.then值正在评估为undefined。当它全部内联时似乎有效,但我理解我应该能够返回顶级promise.all,然后将其视为任何其他承诺。

function createStreamerArray() {
  const regularStreamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]
  const baseURL = 'https://wind-bow.gomix.me/twitch-api'

  return Promise.all(
    regularStreamers.map(streamer => {
      Promise.all([
        Promise.resolve($.getJSON(baseURL + '/users/' + streamer + '?callback=?', null)),
        Promise.resolve($.getJSON(baseURL + '/streams/' + streamer + '?callback=?', null)) 
      ]).then(values => {
        return values
      })
    })
  )
}

createStreamerArray().then(values => console.log(values))

2 个答案:

答案 0 :(得分:1)

首先(最重要的)你需要在.map回调中返回一个值

这可以像这样完成

regularStreamers.map(streamer => {
  // added return
  return Promise.all([
    Promise.resolve($.getJSON(baseURL + '/users/' + streamer + '?callback=?', null)),
    Promise.resolve($.getJSON(baseURL + '/streams/' + streamer + '?callback=?', null)) 
  ])
})

或者,使用箭头功能的简短形式,像这样

//                               { removed
regularStreamers.map(streamer => 
  Promise.all([
    Promise.resolve($.getJSON(baseURL + '/users/' + streamer + '?callback=?', null)),
    Promise.resolve($.getJSON(baseURL + '/streams/' + streamer + '?callback=?', null)) 
  ])
)
// } removed

其次,(纯粹删除不需要的代码)删除多余的

.then(values => {
    return values
})

这导致:



    function createStreamerArray() {
        const regularStreamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
        const baseURL = 'https://wind-bow.gomix.me/twitch-api';
      
        return Promise.all(regularStreamers.map(streamer => Promise.all([
              Promise.resolve($.getJSON(baseURL + '/users/' + streamer + '?callback=?', null)),
              Promise.resolve($.getJSON(baseURL + '/streams/' + streamer + '?callback=?', null)) 
        ])));
    };
    createStreamerArray().then(values => console.log(values));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

你会看到,工作

答案 1 :(得分:0)

您是否尝试在地图功能中添加额外的回报?如果你没有退回第二个Promise.all那么你就不会看到你的价值观。