替代异步标注的承诺?

Alternative to promises of asynchronous callouts?

假设我们有一个简单的前端和(假设 Angular 如果重要的话)和一个后端应用程序。假设前端应用程序执行 get 请求。通常 angular 存储库发出 $http.get 请求,该请求 return 是一个承诺(angular 1)或一个可以转换为承诺的可观察对象(angular 2 或4),然后是承诺的存储库 return。然后 angular 服务看起来像

repository.makeTheGetCall().then(function (response) {
  // process response
}); 

这通常没问题。

1) 但是,如果服务上的所有逻辑都依赖于这 1 个调用怎么办?然后我们基本上将整个服务嵌套在 .then 子句中。

2) 或者如果根据第一个Get 请求的响应,我们进行另一个请求。根据该响应,我们提出另一个请求,依此类推。然后我们将有一堆链接的 then 子句。

这两种情况似乎都很少见,并且都导致出现 'ugly' 代码。是否有任何其他实践可以用来允许异步调用,但不必 return 从存储库层到服务层的承诺?

谢谢:)

您可以使用 async/await。这是经典 .then() 承诺处理的唯一替代方法。

所以,与其这样做:

someServiceMethod() {
  repository.makeTheGetCall().then(function (response) {
    // process response
  }); 
}

你可以这样做:

async someServiceMethod() {
  const response = await repository.makeTheGetCall()
  // process response
}

最酷的是我们没有任何 "callback hell" 的起点,代码现在是扁平化的(在您的列表中排名第一)

此外,如果其中一个 Promise 被拒绝,我们可以在 try/catch 块中处理错误。好处是我们可以在一个地方捕获所有错误。 (在您的列表中排名第 2):

async someServiceMethod() {
  try {  
    const response = await repository.makeTheGetCall()
    const data = await repository.getDataForResponse(response)
    // process data or make another async call
  } catch (err) {
    // process error
  }
}

Good explanation of how to use it