Attack on node. JS Foundation (ii) Promise

Source: Internet
Author: User
Tags readfile throw exception what callback

I. Promise

JS Animation settimeout,setinterval,requestanimationframe,promise

NPM Install Bluebird

JavaScript is characterized by async, JavaScript can't wait, if you implement something that needs to wait, you can't stop there waiting for the result to come back, instead, the bottom line is to use the callback callback: You define a function, This function cannot be called until the result is available. This callback model is not a problem for good code organization, but it can also solve many problems by switching from the original callback to promise, promise as a standard data container, which simplifies your code organization and can be a promise-based architecture. What is Promise?a promise is aThe ". Then ()" Method of the object, which represents the result of an operation may not yet be known, regardless of who accesses this object, can use ". Then ()"method to add a notification that the callback waits for a successful result or failure. So why does this benefit better than callbacks? The standard callback pattern requires a callback function to be provided when we process the request: The requests (URL,function(Error, response) {//handle success or error.});d Osomethingelse (); Unfortunately, this code means that the request function does not know when it will be able to do it itself, and of course it is not necessary, and we finally pass the result through a callback. This causes multiple callbacks to form nested callbacks, or callback traps. Querythedatabase (Query,function(Error, result) {request (URL,function(Error, Response) {Dosomethingelse (response,function(Error, result) {doanotherthing (result,function(Error, result) {request (Anotherurl,function(Error, Response) {...});    });  }); });}); Promise can solve this problem by allowing the lower-level code to create a request and then return an object that represents an unfinished operation that allows the caller to decide what callback to add. What is promise? Promise is an abstraction of asynchronous programming, which is a return value or a proxy object that throws exception, and the general Promise object has a then method, and the then method is how we get the return value (the result value of the successful implementation of the promise, called fulfillment) or throw exception (the reason for rejecting the commitment, called rejection), then is using two optional callbacks as parameters, which we can call onfulfilled and onrejected:varPromise =Dosomethingaync () promise.then (onfulfilled, onrejected) When this promise is solved, that is, after the asynchronous process is complete, Any one of onfulfilled and onrejected will be called, so a promise has the following three different states: pending to be committed-Promise Initial State fulfilled implementation commitment-a commitment to a successful implementation of State rejected refusal of commitment-a state of commitment failure to read a file as a case, here's what to do after reading a file using a callback implementation (output printing): ReadFile (function(err, data) {if(ERR)returnConsole.error (Err) console.log (data)}) If our ReadFile function returns a promise, then we can implement the same logic (output printing) as follows:varPromise =readFile () promise.then (Console.log, console.error) Here we have a value promise represents an asynchronous operation, we can always pass this value promise, Anyone accessing this value can use then to consume it, regardless of whether the value represents the completion or not completion of the asynchronous operation, we can also guarantee that the asynchronous result will not change, because this promise represents the asynchronous operation will only be executed once, The state is either fulfilled or rejected. Understanding promise promise may be different from everyday intuition, in order to understand it, some important principles must be remember:. Then () always returns a new promise, as in the following code:varPromise =ReadFile ()varPromise2 =Promise.then (Readanotherfile, console.error) Here then the parameter readanotherfile, Console.error is an action that represents the success of an asynchronous operation Onfulfilled or after a failed action onrejected, that is, the read file succeeds after the Readanotherfile function is executed, otherwise the failure prints a record error. This implementation is only possible in two. Let's look at the following code as follows:varPromise =ReadFile ()varPromise2 = Promise.then (function(data) {returnReadanotherfile ()//if ReadFile succeeds, execute Readanotherfile},function(Err) {Console.error (err)//if ReadFile is unsuccessful, record, but still execute readanotherfile  returnreadanotherfile ()}) Promise2.then (Console.log, Console.error)//execution results of the Readanotherfile functionbecause then returns a promise, it means that promise can be chain a serial chain flower, which avoids callback to hell: ReadFile (). Then (readanotherfile ). Then (...) Two parts of the promise law must be separated: (1). Then () always returns a new promise, every time you call it, it doesn't matter what the callback does, because. Then () a promise is given to you before the callback is called promise, the behavior of the callback only affects the implementation of the commit promise, if the callback returns a value, Then promise will use that value, if this value is a promise, return the value given to this promise after the implementation of this value, if the callback throws an error, promise will reject the error. (2) The promise returned by. Then () is a new promise, which is different from those of the. then () Promise,promise long chain is sometimes better to hide the fact, no matter how, every time. Then () The call will produce a new promise, and it's important to note that what you really need to consider is the last call you make. Then () may represent failure, so if you do not capture this failure, it is easy to cause your error exception to disappear. Some people think that. Then () series chain calls are similar to the fluent style, but the long promise chain can be confusing and finally cut into meaningful functions:functiongettasks () {return$http. Get (' Http://example.com/api/v1/tasks '). Then (function(response) {returnResponse.data; });} functiongetmytasks () {returngettasks (). Then (function(tasks) {returnFiltertasks (Tasks, {owner:user.username}); });} In this example, two functions each get a promise, carrying a callback function. Interesting promise the same promise can accept any number of callbacks, and when a promise is resolved, all of the callback functions are called, in addition, a promise can even accept a new callback after the implementation is resolved. These callbacks are done in a normal way, allowing us to use callbacks to implement a simple form of caching:vartaskspromise;functiongettasks () {taskpromise= Taskpromise | |Gettasksfromtheserver (); returnTaskpromise;} In this case, the Gettasks () function can be called any number of times, and it always returns the promise of the copper tooth, where the function Gettasksfromtheserver () is only called once. 

Attack on node. JS Foundation (ii) Promise

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.