Javascript ES6承诺序列,XHR用于令牌,然后再次XHR

Javascript ES6承诺序列,XHR用于令牌,然后再次XHR,javascript,Javascript,我需要做一个承诺序列。我想使用基于标准的方法(ES6?)。实现这一目标的最佳方式是什么getToken()和httpReq()返回承诺,clock.now只返回now的unix时间戳。我的代码如下所示(简化/浓缩)。我明白我需要用一个单一的捕获物来压扁承诺链。。。有人能用一种干净、易读、不聪明的ES6方式来说明吗 // we don't have a good token so we need to get one first, then GET the resource. getToken(h

我需要做一个承诺序列。我想使用基于标准的方法(ES6?)。实现这一目标的最佳方式是什么
getToken()
httpReq()
返回承诺,
clock.now
只返回now的unix时间戳。我的代码如下所示(简化/浓缩)。我明白我需要用一个单一的捕获物来压扁承诺链。。。有人能用一种干净、易读、不聪明的ES6方式来说明吗

// we don't have a good token so we need to get one first, then GET the resource.
getToken(host, port, auth).then(function(token) {

  httpReq(method, host, port, path, token).then(function(data) {
    console.log(data);
  }, function(status) {
    console.log(status);
  });


}, function(status) {
  console.log(status);
});

你很接近。我是这样做的:

getToken(host, port, auth) // Promise for token
  .then(token => httpReq(method, host, post, path, token)) // Promise for data, using token
  .then(data => console.log(data)) // final step
  .catch(err => console.error(err)); // error handling for all steps in the chain
如果没有箭头功能:

getToken(host, port, auth)
  .then(function(token) { return httpReq(method, host, post, path, token); })
  .then(function(data) { return console.log(data); }) // not strictly necessary. But
                                                      // strictly equivalent to above
  .catch(function(err) { return console.log(err); });
需要注意的几件事:

  • 不要嵌套
    .then()
    子句。相反,从第一个
    .then()
    子句返回一个承诺,并在外部继续该链
  • 使用承诺时,确保始终返回承诺。不要让
    .then()
    子句没有返回值,也不要让承诺函数没有返回值
  • 使用箭头函数可以使上述两点变得简单

你很接近。我是这样做的:

getToken(host, port, auth) // Promise for token
  .then(token => httpReq(method, host, post, path, token)) // Promise for data, using token
  .then(data => console.log(data)) // final step
  .catch(err => console.error(err)); // error handling for all steps in the chain
如果没有箭头功能:

getToken(host, port, auth)
  .then(function(token) { return httpReq(method, host, post, path, token); })
  .then(function(data) { return console.log(data); }) // not strictly necessary. But
                                                      // strictly equivalent to above
  .catch(function(err) { return console.log(err); });
需要注意的几件事:

  • 不要嵌套
    .then()
    子句。相反,从第一个
    .then()
    子句返回一个承诺,并在外部继续该链
  • 使用承诺时,确保始终返回承诺。不要让
    .then()
    子句没有返回值,也不要让承诺函数没有返回值
  • 使用箭头函数可以使上述两点变得简单

我的意思是,在我看来,他的尝试非常接近正确。我编辑这篇文章是为了澄清。有趣的是,在查看问题和答案时,注意到用户(包括主持人)可能的不同观点。从这里的vantage,看起来好像您在引用问题中的用户图像。谢谢。“你有没有可能在没有箭的情况下展示它?”RonRoyston当然是说,在我看来,他的尝试非常接近正确。我编辑这篇文章是为了澄清。有趣的是,在查看问题和答案时,注意到用户(包括主持人)可能的不同观点。从这里的vantage,看起来好像您在引用问题中的用户图像。谢谢。“你有没有可能在没有箭的情况下展示它?@RonRoyston当然有看到