All calls to Nodejs are almost completely asynchronous, and all IO operations are known by callback functions. If an asynchronous call relies on another asynchronous call, it is possible to fall into the legendary callback hell if there is no promise.
Bluebird implements the transformation of asynchronous callbacks into chained notation, and extends the APIs such as catch, finally, bind, and so on, which can help us focus on the error of each query.
The information about promise and Bluebird found on the internet is basically about principle and theory, this article introduces Bluebird practical use example. In practice, we only use promisify classes and methods that need to be chained, and the code is as follows:
//Introduction of database Operation ModulevarMongoDB = require ("./db") Promise= Require ("Bluebird") ;varMongoose = require ("Mongoose");varSchema =Mongoose. Schema;//declaring the user schema structurevarUserschema =NewSchema ({user_id:string, password: {type:string,default:""}, Nickname: {type:string,default:""}, Introduction: {type:string,default:""}, Age: {type:string,default:""}, Gender: {type:string,default:""}, });//give the user class an interfacevarUser = Mongoose.model ('User', Userschema);//The user class of Promise and its methodsPromise.promisifyall (User); Promise.promisifyall (User.prototype); Module.exports= User;
In addition, the following use of the same set of the table will need to do the above processing
Use the following methods:
Room.findone ({type:'Pano'}) //. EXEC (). Then (function () {Console.log ('Rooms:', Guest)
Instead of returning the query results in a callback, the query results are passed to the next one. Thenreturnuser.findone ({_id:room.creator}); }). Then (function (user) {Console.log ('the user receives the previous. Then passed variables:', user)}) .Catch(function (e) {//Handling Error }) .finally(function () {//Final Code Execution})
Mongoose and Bluebird Use cases