Recently saw a lot of articles are talking about promise, why Asynchronous Programming now receive so much attention? And why asynchronous programming to choose Promise ?
First of all, the reason why asynchronous programming is so important is that JavaScript is moving towards standardization, normalization (MVC, module, OOP), so some of the normative constraints in traditional programming areas are becoming more and more important, And JavaScript itself is about "async", either the browser or node server side, most of the API is through the "event" to separate the request and return value. To put it simply: JavaScript is valued, and it itself is too much asynchronous programming.
Then there is the second question: Why should asynchronous programming choose promise? The above mentioned "event", The "event" is bound to leave the callback. and callback, as the traditional implementation of asynchronous programming has three major methods (callback, event monitoring, publish/subscribe) One of the implementation is not very neat, a layer of callback nesting enough to get you into a "callback hell", greatly reducing the readability of the program logic . So at this time, thePromise Savior (Prophet) appeared,Promise is a COMMONJS Working group standard developed a mechanism, in order to provide a unified interface for asynchronous programming, the implementation of standardized asynchronous programming management, and when/ Then the chain of writing makes the process clear. Its role scenario is primarily for time-consuming scenarios (the problem in node is more prominent because node itself is asynchronous programming-driven), such as Ajax, sockets, and local time-consuming computations that interact with the background.
After a brief introduction, let's look at the workflow (figure):
Promise is an instance object that receives one or more parameter requests ( when multiple requests are used when (F1,F2)) and ultimately returns a finite state machine with the following states:
- Complete (Resolve)
- Negation (rejected)
- Wait (pending)
After returning the status and then (Onresolve,onreject) to the corresponding state to make the corresponding ONXXX callback processing, then (Onresolve,onreject) is a chain method, let the user handle the success of the failure respectively.
There is a Deffered object (so far, my understanding of deffered is still vague)
- Provides resolve and rejected methods to complete a promise
Finally, a list of common frameworks that support promise:$.deferred () in jquery ,$q.defer in AngularJs (), The promise abstract base class in Dojo and the Promise Library on server-side node
Or you can build a promise framework for yourself.
Talk about JavaScript asynchronous programming and the new implementation method--promise