Promise of Bluebird-NodeJs
Promise is a way for asynchronous code to implement control flow. This method can make your code clean, readable, and robust. For example, the callback code you use to asynchronously process file events:
fs.readFile('directory/file-to-read', function(err, file){ if (error){ //handle error } else { //do something with the file }});
You may have heard that Node will soon fall into callback hell. The above is the reason. As a node developer, you will encounter a lot of asynchronous code and many callbacks ). These Callbacks are relatively simple. However, you will need to continue to perform other actions after an action is completed, so the callback will be continuously nested. You will soon find the code hard to read, not to mention maintenance. For example:
fs.readFile('directory/file-to-read', function(err, file){ if (error){ //handle error } else { //do something with the file fs.mkdir('directory/new-directory', function(err, file){ if (error) { //handle error } else { //new directory has been made fs.writeFile('directory/new-directory/message.txt', function(err, file){ if(error) { // handle error } else { // File successfully created } }); } }); }});
In the preceding example, I want to asynchronously read a file, create a directory, and create a file. You can see how ugly nested code this simple three-step task has become, especially when you add logical control to the code. Why do we need to use the code above Promise in node as an example? We will explore how to use Promise to solve the problems mentioned above:
fs.readFileAsync('directory/file-to-read') .then(function(fileData){ return fs.mkdirAsync('directory/new-directory'); }) .then(function(){ return fs.writeFileAsync('directory/new-directory/message.txt'); })
Promise provides us with a clearer and more robust way to write asynchronous code. The initial method returns a promise, which can call the 'then' method. You can call more 'then' after 'then '. Each 'then' can access the information returned by the previous 'then. You can call another 'then' for the example returned by each 'then' method '. This is often another asynchronous call. Promise also makes it easier for you to break down code into multiple files. For example:
function readFileandMakeDirectory(){ return fs.readFileAsync('directory/file-to-read') .then(function(fileData){ return fs.mkdirAsync('directory/new-directory'); });}//The following will execute once the file has been read and a new directory has been madereadFileandMakeDirectory() .then(function(){ return fs.writeFileAsync('directory/new-directory/message.txt'); })
It is easy to create a method that returns promise. It is useful when you need to break down the code into different files. For example, you may have a route to read a file, read its content, and return the content in json format. You can break down the code into multiple components that return promise.
//routes/index.jsvar router = require('express').Router();var getFileExcerpt = require('../utils/getFileExcerpt')router.get('/', function(){ getFileExcerpt.then(function(fileExcerpt){ res.json({message: fileExcerpt}); });});module.exports = router;//utils/getFileExcerpt.jsvar Promise = require('bluebird');var fs = Promise.promisifyAll(require('fs'));module.exports = function getPost(){ return fs.readFileAsync(file, 'utf8').then(function(content){ return { excerpt: content.substr(0, 100) } });}
The above Code clearly indicates that any returned 'then' can be called later '. It is very easy to use promise to handle errors. When an error occurs during the execution of a bunch of 'then' methods, Bluebird will find the latest. catch Method for execution. You can embed the catch Method in the 'then' chain. The preceding example can be rewritten:
fs.readFileAsync('directory/file-to-read') .then(function(fileData){ return fs.mkdirAsync('directory/new-directory'); }) .then(function(){ return fs.writeFileAsync('directory/new-directory/message.txt'); }) .catch(function(error){ //do something with the error and handle it });
You can use catch to handle errors. However, if the module I want to use does not return promise, you will notice that the above example uses 'fs. writeFileAsync 'and 'fs. mkdirAsync '. If you check the node documentation, you will see that these methods do not exist. FS does not return promise. Even so, bluebird provides a very useful function for promise-based modules that do not return promise. For example, the promise fs Module simply requires the require bluebird module and a promise fs module. Var Promise = require ('bluebird'); var fs = Promise. promisifyAll (require ('fs'); Create your own Promise because you can promise the module, so you don't need to write a lot of code to create promise. Then, even so, it is necessary to know how to create it. To create a promise, you must provide the resolve and reject callback methods. Each of them needs to be passed:
//myPromise.jsvar Promise = require('bluebird');module.exports = function(){ return new Promise(function(resolve, reject){ tradiationCallbackBasedThing(function(error, data){ if (err) { reject(err); } else { resolve(data) } }); });}
This completes promise. Next, you can use this technology to write all your desired promise into the promise form. Test Promise when I test the server code, my favorite frameworks are mocha and chai. Note that when testing asynchronous code, you need to tell mocha when the asynchronous code is executed. Otherwise, he will continue to perform the following tests, and an error will occur. In this case, you only need to simply call the callback method provided by mocha in the it Section:
it('should do something with some async code', function(done){ readPost(__dirname + '/../fixtures/test-post.txt') .then(function(data){ data.should.equal('some content inside the post'); done(); }) .catch(done);});
Promise is very useful. It is strongly recommended that you use promise when writing asynchronous code using node.