How to package the Callback interface into a Promise interface

Source: Internet
Author: User

I've been looking at node. js for a while, and in the development process we often call some asynchronous interfaces, usually in the last parameter of the interface passing in a callback function that can be used to handle exceptions, not exceptions. The approximate pattern is as follows:

1 var fs = require ("FS"); 2 fs.readfile (filename, "binary", function (err, file) {3    if (err) {4         //Abnormal case 5   }else{6       //Normal 7     } 8 });            

However, this kind of writing encounters the more complicated logic, it is easy to appear callback hell problem.

When node. JS needs to execute asynchronous logic sequentially, it generally takes the following delivery style, which is to encapsulate the subsequent logic in the callback function as the parameter of the starting function, nesting by layer. Although this style can improve CPU utilization and reduce wait time, but when the subsequent logical steps are more, it will affect the readability of the code, the result code modification maintenance becomes very difficult. According to this code, it is generally called "Callback hell".

The asynchronous interface is handled in a way that relies on promise, and returns the promise directly to the fetch referred to in the previous article.

How do I turn the callback interface into an promise interface?

varPromisify =functionpromisify (FN, receiver) {return function() {           for(var_len = argument.length, args = Array (_len), _key = 0; _key<_len; _key++) {Args[_key]=Arguments[_key]; }            return NewPromise (function(Resolve, Reject) {fn.apply (receiver, [].concat (args,[function(Err, res) {returnErr?reject (Err): Resolve (RES);     }]));     });         };}; 

By promisify This function, the interface can be converted.

The above template can be changed to the following form:

 1  var  fs = require ("FS" ); 2  var  readfilepromise = promisify ( Fs.readfile, FS); //  wrapper for Promise interface  3  readfilepromise (filename, "binary"). Then ( function   4  //  normal  5 }). catch  (function   (err) { 6   exception  7 }) 

Special cases

Some interfaces that are designed unreasonably may pass multiple values to the callback function, such as:

1 var function (foo, callback) {2       if (Success) {3             callback (null, file1, file2); 4       } Else {5            callback (ERR); 6       }7 }

Obviously this interface passed File1,file2 two values, there is no way to use the above method, with the above interface conversion there is no way to get to the file2 data.

This is only possible with manual packaging.

Improve performance

You can use a high-performance promise library to improve performance. such as: Bluebird. The simple contrast test found that Blurbird's performance was about 3 times times the V8 built-in Promise.

Replace the built-in promise:

    • Global. Promise = require ("Bluebird");

If the project uses Babel compiled ES6 code, you can replace it in the following way: If the project uses Babel compiled ES6 code, you can replace it in the following way:

    • require (require (" Bluebird ");
    • global. Promise = require ( "Bluebird");
Babel is used to convert your JavaScript code to your JavaScript code: myJavaScript("foobar"); the JavaScript after conversion is like this myNewTransformedJavaScript("yay!");

Original address: http://welefen.com/post/how-to-convert-callback-to-promise.html

How to package the Callback interface into a Promise interface

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.