Initial JavaScript Promises II

Source: Internet
Author: User

Initial JavaScript Promises II
Error Handling in asynchronous programming is human and ideal, just as many programming languages have implemented the following error handling methods: try {var val = JSON. parse (fs. readFileSync ("file. json ");} catch (SyntaxError e) {// json syntax error console. error ("not in json format");} catch (Error e) {// other types of error console. error ("file cannot be read")} Unfortunately, JavaScript does not support the above method, so "smart monkey" may write the following code: try {// code} catch (e) {if (e instanceof SyntaxError) {// handle} else {// handle} I believe no one will like the second code, however, traditional JavaScript can only help you here. The above code is in synchronous mode. What is the error handling in asynchronous mode? Fs. readFile ('file. json', 'utf8', function (err, data) {if (err) {console. error ("file not readable")} else {try {var json = JSON. parese (data)} catch (e) {console. error ("not in json format") ;}}) reminder: In node. in js, you should try to avoid using the synchronization method. By carefully comparing the differences between the first and third sections of the code, you will find that such a simple code has been indented three times! If other asynchronous operations are added, it is inevitable to encounter callback hell. Use Promise to handle errors. Suppose fs. readFileAsync is fs. what does readFile's Promise version mean? Recall: fs. the returned result of the readFileAsync method is a Promise object fs. the returned results of the readFileAsync method have a then method fs. the readFileAsync method accepts parameters and fs. readFile is consistent, except that the last callback function returns the Promise object, which means that the fs. readFileAsync does not immediately execute asynchronous operations, but calls its then method for execution. The callback function accepted by the then method is used to process the correct returned results. So use fs. readFileAsync is used as follows: // Promise fs. readFileAsync ('file. json ', 'utf8 '). then (function (data) {console. log (data)}) OK. Let's continue to handle this topic. Since Promises/A + only specifies the unique then method for the Promise object, there is no catch or error method specifically, we will continue to use bluebird. // Promise version fs with error handling. readFileAsync ('file. json ', 'utf8 '). then (function (data) {console. log (data )}). catch (SyntaxError, function (e) {// code here }). the code above catch (function (e) {// code here}) has no nested callback, which is basically the same as the writing mode of the first code in this article. Magic Promisify Note: Next we will see how to promisify the fs. readFileAsync method, still using bluebird. Var Promise = require ('bluebird') fs. readFileAsync = Promise. promisify (fs. readFie, fs) is so easy! There is also a more powerful method for bluebird, that is, promisify's advanced version promisifyAll, such as: var Promise = require ('bluebird') Promise. after promisifyAll (fs) executes the above Code, all asynchronous methods under the fs object will generate a Promise version method, such as fs. readFile corresponds to fs. readFileAsync, fs. mkdir corresponds to fs. mkdirAsync, and so on. In addition, in Promise versions, except for the last parameter (callback function), other parameters correspond to the original function. Do not forget to pass the original parameters when calling the function. Promisification for fs cannot satisfy me. I need more magical magic: // redisvar Promise = require ("bluebird"); Promise. promisifyAll (require ("redis"); // mongoosevar Promise = require ("bluebird"); Promise. promisifyAll (require ("mongoose"); // mongodbvar Promise = require ("bluebird"); Promise. promisifyAll (require ("mongodb"); // mysqlvar Promise = require ("bluebird"); Promise. promisifyAll (require ("mysql/lib/Connection "). prototype ); Promise. promisifyAll (require ("mysql/lib/Pool "). prototype); // requestvar Promise = require ("bluebird"); Promise. promisifyAll (require ("request"); // mkdirvar Promise = require ("bluebird"); Promise. promisifyAll (require ("mkdirp"); // winstonvar Promise = require ("bluebird"); Promise. promisifyAll (require ("winston"); // Nodemailervar Promise = require ("bluebird"); Promise. promisifyAll (require ("nodemaile R "); // pgvar Promise = require (" bluebird "); Promise. promisifyAll (require ("pg "));//... hey, are you trembling now? Note: If you are using mongoose, you may need mongoomise in addition to bluebird. It has the advantages of accepting arbitrary Promise Library (Q/when. js/RSVP/bluebird/es6-promise, etc.) can be used to customize the static private method of Model promisify, while bluebird. promisifyAll does not support mongoomise + bluebird, which is slightly inferior to using only bluebird, and may be better. We have already used mongoomise + bluebird in the production environment, so far everything is well. (To be continued at a.m. on February 15)

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.