【问题标题】:ES6 Promise Sequence, XHR for Token then XHR Again [duplicate]ES6 Promise Sequence,XHR for Token 然后 XHR Again [重复]
【发布时间】:2017-01-08 05:56:21
【问题描述】:

我需要做一个承诺序列。我想使用基于标准的方法(ES6?)。实现这一目标的最佳方法是什么? getToken()httpReq() 返回承诺,clock.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);
});

【问题讨论】:

标签: javascript


【解决方案1】:

你很亲密。以下是我的做法:

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() 子句返回一个 Promise,并在外面继续链。
  • 使用 Promise 时,请确保始终返回一个 Promise。永远不要留下没有返回值的 .then() 子句,也永远不要留下没有返回值的 Promises 函数。
  • 使用箭头函数可以轻松实现上述两个点。

【讨论】:

  • 我的意思是,在我看来,他的尝试看起来非常接近正确。我已经编辑澄清。
  • 在查看问题和答案时注意到用户(包括版主)可能的不同观点很有趣。从这里的有利位置,您似乎在引用问题中的用户图像。
  • 谢谢。你有没有机会在没有箭头的情况下显示它?
  • @RonRoyston 确定
猜你喜欢
  • 2019-07-23
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-26
相关资源
最近更新 更多