当前位置:网站首页>What is promise? What are the benefits of promise

What is promise? What are the benefits of promise

2022-07-24 00:34:00 Ssie-

1、 What is? Promise

promise Is the solution to asynchrony , It's essentially a constructor , You can instantiate an object with it . The object has resolve、reject、all, Prototype has then、catch Method .promise Objects have three states :pending( Have in hand )、fulfilled( success )、rejected( Failure )

Promise The object has two characteristics :

(1) The state of the object is not affected by the outside world .Promise The object represents an asynchronous operation , Only the result of asynchronous operation can determine Promise Object state , No other operation will change this state . This can be compared with Promise Its name is understood together ,Promise yes “ promise ” It means , Says nothing else can be changed .

(2) Once the status changes , Will not change again . And its state changes only by (pending->fulfilled、

pending->rejected) And as long as one of these two situations occurs , The state is fixed .

2、Promise The advantages of :

(1) Support chain calls ( Asynchronous operations can be displayed synchronously ) Avoid going back to hell

What is callback hell ?

Multiple callback functions are nested layer by layer , The result returned asynchronously by the outer callback function is the execution condition of the inner callback function

The drawback of callback hell ?

1、 Readability 、 Poor maintainability

2、 Not convenient for exception handling

What is a callback function ?

The callback function is abbreviated as “ Callback ”, It can be understood as “ Go back and call the function ”. It is taken as a parameter , Pass it to another function , After that function is executed , Then execute the parameter passed in .

Why should there be a callback function ?

Because you don't know when the sub thread will finish executing , At this time, you need a callback function , Notify the main thread after it finishes executing .

(2) Specifying callback functions is more flexible : Previously, we had to specify a callback before defining an asynchronous task , Now you can specify the callback after the asynchronous task is executed .

Promise The shortcomings of ?

1、 Cannot cancel it , Once established, it will be executed immediately , There is no way to cancel halfway

2、 If you don't set a callback function for it , Internal thrown errors cannot be displayed

3、 When in pending In state , It's impossible to know where the current progress is ( Is it just beginning or just ending )

( Because I am right Promise I haven't really understood , So record )

原网站

版权声明
本文为[Ssie-]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230937433725.html