在承诺中获得a的结果

时间:2018-01-01 12:21:14

标签: javascript promise es6-promise

我正在尝试处理以下问题。

在下面的代码中,我试图从内部then函数中获取结果。我希望let online函数将返回onlineResult.stream。但是,它返回:

enter image description here

如果期望: enter image description here

null当它为空时。

var baseUrl = "https://wind-bow.gomix.me/twitch-api";
var channels = [
  "ESL_SC2",
  "OgamingSC2",
  "cretetion",
  "freecodecamp",
  "storbeck",
  "habathcx",
  "RobotCaleb",
  "noobs2ninjas"
];

function fetchChannels(channels) {

  var listItems = [];
  if (Array.isArray(channels)) {

    const results = channels.map(channel =>
      $.getJSON(`${baseUrl}/channels/${channel}?callback=?`)
    );

    Promise.all(results).then(values => {
      values.forEach(val => {

        let online = $.getJSON(`${baseUrl}/streams/${val.name}?callback=?`)
          .then(onlineResult => {
            return onlineResult.stream;
          })
        console.log(online);
        listItems.push([val.name, val.logo]);
      });
    });
  }
}

fetchChannels(channels);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1 个答案:

答案 0 :(得分:0)

您可能要做的是在第一个频道请求中添加then(),并在到达时立即获取与该频道相关联的流

类似的东西:

&#13;
&#13;
var baseUrl = "https://wind-bow.gomix.me/twitch-api";
var channels = ["ESL_SC2", "OgamingSC2"];

function fetchChannels(channels) {

  if (!Array.isArray(channels)) {
    return Promise.reject('No channels array')
  } else {
    const channelPromises = channels.map(channel =>
      $.getJSON(`${baseUrl}/channels/${channel}?callback=?`)
      .then(fetchStream)
    );

    return Promise.all(channelPromises)
  }

  function fetchStream(channelResult) {

    return $.getJSON(`${baseUrl}/streams/${channelResult.name}?callback=?`)
      .then(streamResult => {
        return streamResult.stream;
      }).then(stream => {
        // adding the result of stream request as property of channel request ... adapt as needed
        channelResult.stream = stream;
        return channelResult
      })
  }
}

fetchChannels(channels)
  .then(res => console.log(res))// array of channel requests, each has a `"stream"` property
  .catch(err => console.log(err))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;