假设我们有一个简单的前端和一个后端应用程序(如果重要的话让我们假设 Angular)。假设前端应用程序执行 get
请求。通常 Angular 存储库发出一个 $http.get
请求,返回一个 promise ( Angular 1)或一个可以转换为 promise 的可观察对象( Angular 2 或 4),然后存储库返回该 promise .然后 Angular 服务看起来像
repository.makeTheGetCall().then(function (response) {
// process response
});
这通常没问题。
1) 但是,如果服务上的所有逻辑都依赖于这 1 个调用怎么办?然后我们基本上将整个服务嵌套在一个 .then 子句中。
2) 或者如果基于第一个 Get 请求的响应,我们发出另一个请求会怎样。根据该响应,我们提出另一个请求,依此类推。然后我们将有一堆链接的 then 子句。
这两种情况似乎都很少见,并且都会导致看起来“丑陋”的代码。是否有任何其他实践可以用来允许异步调用,但不必将 promise 从存储库层返回到服务层?
谢谢你:)
最佳答案
您可以使用async/await
。它是经典 .then()
promise 处理的唯一替代方案。
所以,与其这样做:
someServiceMethod() {
repository.makeTheGetCall().then(function (response) {
// process response
});
}
你可以这样做:
async someServiceMethod() {
const response = await repository.makeTheGetCall()
// process response
}
最酷的是我们没有任何“回调 hell ”的起点,代码现在是扁平的(在你的列表中排名第一)
此外,如果其中一个 Promise 被拒绝,我们可以在 try/catch
block 中处理错误。好处是我们可以在一个地方捕获所有错误。 (在您的列表中排名第 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
}
}
关于javascript - 替代异步标注的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46964834/