javascript - 通过 promise 链传递结果无法访问?

标签 javascript

根据下面的代码,我将所有数据链接起来,直到最后我希望将数据渲染到 View ,但是使用 .catch 我发现召唤器在最终函数中无法访问。

getSummonerData(req.params.playerName)
.then(function(summoner) {
  return getMatchIds(summoner[0].id);
})
.then(function(matchIds) {
  return getGameData(matchIds);
})
.then(function(gameData) {
  res.render('profile', {player:summoner, games:gameData});
})
.catch(function(e) {
  console.log(e);
});

最佳答案

在您的代码中,summoner 只能由包含您对 getMatchIds 的调用的 then 回调访问,而不能在其他地方访问。要稍后访问,您必须 1) 从 then 回调中将其与游戏数据一起返回,或者 2) 嵌套需要它的 then 回调< em>在该回调中。

后者可能是更容易的:

getSummonerData(req.params.playerName)
.then(function(summoner) {
  return getMatchIds(summoner[0].id)
    .then(function(matchIds) {
      return getGameData(matchIds);
    })
    .then(function(gameData) {
      res.render('profile', {player:summoner, games:gameData});
    });
})
.catch(function(e) {
  console.log(e);
});

关于javascript - 通过 promise 链传递结果无法访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41659554/

相关文章:

javascript - 将表单输入限制为单个数字

javascript - Ext.onReady() 与 $(document).ready()

javascript - Fancybox form ajax提交,只有一个ajax请求

javascript - Firebase 具有 useeffect 清理功能

javascript - 查找离我的地理位置最近的标记 Google Maps API V3

Javascript Promise 返回值

javascript - Express + EJS - 将参数传递给 EJS View

javascript - DeviceInformation.findAllAsync DeviceInformation 返回不正确的名称属性

javascript - D3 V3 到 D3 V4 树数组使用层次结构重新排序错误

javascript - 如何从外部网站加载DIV?