[英]Correct use of Promises and Error Handling
I have the task of writing a WebApp with angular, where a prototype exists. 我的任务是在存在原型的情况下使用angular编写WebApp。 As I have no experience with Typescript and asynchronous programming, I am not sure how to approach this in the best way.
由于我没有Typescript和异步编程的经验,因此我不确定如何以最佳方式实现这一目标。
In the prototype a handshake is performed, which is a sequence of calculations and HTTP requests. 在原型中,将执行握手,握手是一系列计算和HTTP请求。 All functions (even those that just calculate something) return a Promise containing the function and resolve or reject as a result.
所有函数(甚至那些仅计算某些函数的函数)都返回一个包含该函数的Promise,并因此解决或拒绝该函数。
These function are combined in a long chain of .then
, which also handles the Errors. 这些功能组合在
.then
的长链中,该链也处理错误。 This looks rather strange and I am not sure, what really happens there under the hood: 这看起来很奇怪,我不确定引擎盖下到底发生了什么:
this.startHandshake()
.then((buf) => this.calculateSomthing(buf)
.then((buf2) => http.sendData(buf2)
..., // this goes on many levels
(e:Error) => this.handleError(e)),
(e:Error) => this.handleError(e))
.catch((e: Error) => { /* Error Handling */ });
My Questions are: 我的问题是:
I would suggest to you about reading some more about promises and how to use them, but anyway, your questions: 我会建议您阅读更多关于诺言以及如何使用诺言的信息,但是无论如何,您都会提出以下问题:
this.startHandshake()
.then((buf) => this.calculateSomthing(buf))
.then((buf2) => http.sendData(buf2))
.then(() => {all the reset} )
.catch((e: Error) => { ... });
yes and no, usually you would prefer to keep the promises one after another, and not inside, so your code should something like this: 是的,不是,通常您希望一个接一个地履行承诺,而不是遵守承诺,因此您的代码应如下所示:
what happen inside the promise is synchronize, what happen between the promises is aync 发生什么事的承诺里面同步,承诺之间发生什么事是aync
as i said before, you might just put synchronized code inside the promise, about the error handling you might need to read about Promise.reject , witch give you the ability to reject the promise manually 如我之前所说,您可能只是将同步代码放入了Promise中 ,关于您可能需要阅读有关Promise.reject的错误处理,女巫使您能够手动拒绝Promise
the async\\await is exactly the same as Promise, it's only sugar syntax. async \\ await与Promise完全相同,只是糖语法。 i prefer the async\\await syntax, but the setup of the project require a little bit more attention (Promise is built in in most of the browsers, async await isn't)
我更喜欢async \\ await语法,但是项目的设置需要更多注意(Promise内置在大多数浏览器中,而async await不是内置的)
Edit : something isn't working with the code formatting, so i moved it up above the question 编辑 :某些代码格式不起作用,所以我将其移至问题上方
Good Luck! 祝好运!
阅读有关回调地狱的知识可以为您提供有关如何解决嵌套问题的一些见解。
let say you have multiple functions that each one return a Promise 假设您有多个函数,每个函数都返回一个Promise
f1(p1: any):Promise<any> {}
f2(p2: any):Promise<any> {}
f3(p3: any):Promise<any> {}
If you want to chain all your methods and execute one after other the best approach (in my opinion) is write something like this 如果您想链接所有方法并一个接一个地执行,最好的方法(在我看来)是这样写的
const p1 = {} // my firt parameter
f1(p1).then((result)=>f2(result))
your code will be executed once you call the then
method 一旦调用
then
方法,您的代码将被执行
to handle all the errors from all the method you use ,you should use the catch
method after call then
要处理所有使用的方法中的所有错误,应在调用后使用
catch
方法, then
f1(p1).then((result)=>f2(result)).catch((err:Error)=>{ /** do something*/ })
I case you want to manage a specific error coming from one your functions then I suggest you do something like this 如果您想管理某个函数产生的特定错误,那么我建议您做这样的事情
f1(p1).then((result)=>f2(result).catch((err)=>Promise.resolve(optionalResult))).catch((err:Error)=>{ /** do something*/ })
this process won't brake your chain and will continue with the rest of the methods 这个过程不会使您的链条停滞不前,并将继续其余方法
Other think you can do is execute promises in parallel using Promise.all()
method like this 其他认为您可以做的是使用
Promise.all()
方法并行执行promise
Promise.all([f1(p1), f2(p2), f3(p3)]).then((results:any[])=>{ ...})
this function will return a array with all the results 该函数将返回一个包含所有结果的数组
In case you want to throw a error or just stop the chain you can use Promise.reject
method 如果您想抛出一个错误或只是停止链,可以使用
Promise.reject
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.