简体   繁体   English

正确使用承诺和错误处理

[英]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: 我的问题是:

  1. Is this Code pattern common for this kind of problem? 这种代码模式是否常见于此类问题?
  2. I read that Promises are handled in a single threaded way. 我读到Promise以单线程方式处理。 What does that mean for Promises that just calculate something (no http request, no timer) ? 这对仅计算某些内容的承诺(没有HTTP请求,没有计时器)意味着什么? When is the function in the Promise executed? Promise中的功能何时执行? Is it instantly, put in a queue for a time when the original code is finished, or is the javascript engine scheduling those two lines of execution? 是立即完成,还是在原始代码完成后放入队列,还是JavaScript引擎调度了这两行执行?
  3. I would prefer to write some of the functions synchronously, but then I need a way to handle errors. 我宁愿同步编写一些功能,但随后我需要一种处理错误的方法。 The most obvious - exceptions - does not seem to play well with promises. 最明显的例外-似乎不能兑现承诺。
  4. Is maybe async / await applicable in my case to make the code more readable? 也许异步/等待适用于我的情况,以使代码更具可读性? How would errors be handled? 错误将如何处理? Is it combinable with exceptions? 它可以与异常组合吗?

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) => { ... });
  1. yes and no, usually you would prefer to keep the promises one after another, and not inside, so your code should something like this: 是的,不是,通常您希望一个接一个地履行承诺,而不是遵守承诺,因此您的代码应如下所示:

  2. what happen inside the promise is synchronize, what happen between the promises is aync 发生什么事的承诺里面同步,承诺之间发生什么事是aync

  3. 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

  4. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM