Operation MySQL in node. js using Promise

Source: Internet
Author: User

Recently, while learning about node. js, I've heard that the callback hell results have been around for a week. So take the time to learn a little bit about promise. Although there are async/await, CO, generators and other options, but because I base poor, and time problems so decided to use good promise first.

You can choose to use the original, of course, it is best to use Bluebird, heard that performance is much better than the official, and there are additional features: promisifyAll、 promisify

Official case:

var fs = Promise.promisifyall (Require ("FS")), Fs.readfileasync ("Myfile.js", "UTF8"). Then (function (contents) {    Console.log (contents);}). catch (function (e) {    console.error (e.stack);});

  

First, if you want to use the. Then statement only after the Promise object, you must modify the original connection code so that he returns a Promise object. Of course

Use the original MySQL connection code:

var mysql=require ("MySQL") var settings=require ('. /settings '); var pool = Mysql.createpool ({    host:settings.host,    user:settings.user,    password: Settings.password,    database:settings.db,    port:settings.port}); Module.exports=function (Sql,callback) {    pool.getconnection (function (err,conn) {        if (err) {            callback (err,null,null);        } else{            conn.query (sql,function (err,rows,fields) {                //release connection                conn.release ();                Event-Driven callback                callback (Err,rows,fields)            ;        });};    

Change the following code to:

Module.exports=function (SQL) {    return new Promise (function (resolve, reject) {        pool.getconnection (function ( Err,conn) {            if (err) {                reject (err);            } else{                conn.query (sql,function (err,rows,fields) {                    //release connection                    conn.release ();                    Pass Promise Callback Object                    Resolve ({"Err": Err,                            "Rows": Rows,                            "Fields": Fields}    );});});});};

Here's a look at the 2 keywords reject and resolve:

Reject: Throws an exception, receives and processes him in the nearest. catch ().

Resolve: Passes data to the next. Then statement.

Here I use resolve ({"Err": Err, "Rows": Rows, "Fields": Fields}); Because resolve cannot pass multiple objects, it is possible to consider arrays or combine them into one object.

Use case:

var express = require (' Express '); var query=require ('.. /module/mysql '); var json=require (' JSON '); var router = Express.    Router (); Router.post ('/uploads/uploadfactoryinfo ', function (req, res, next) {var factoryname=req.body.factoryname;    var factoryadress=req.body.factoryadress;    var contactinfo=req.body.contactinfo;    var Remark=req.body.remark;    var updatedate=req.body.updatedate;    var Handleusername=req.session.loginuser;    Determine if the name of the manufacturer is duplicated, and if so, return the error message query ("SELECT * from Managersystem.factoryinfo where factoryname= '" +factoryname + "';"). Then (data) {if (data.rows[0]!=undefined) {Res.json} ({message: ' The manufacturer's information has been entered!)            ‘});        Return }}). Then (function () {query ("INSERT into Managersystem.factoryinfo (Factoryname, Infoupdatetime, ContactInfo, Address, remark) "+" VALUES (' "+factoryname+" ', ' "+updatedate+" ', ' "+contactinfo+" ', ' "+factoryadress+" ', ' "+r emark+ "');");}). Then (function () {Query ("Select * FROM Managersystem.factoryinfo where factoryname= ' "+factoryname +" '; "). Then (the function (data) {var sql = "INSERT into Managersystem.useractionrecords (' handleusername ', ' Handletablen  Ame ', ' Handletableid ', ' olddata ', ' NewData ', ' action ', ' dateTime ') ' + ' VALUES (' + Handleusername + ',            ' Factoryinfo ', ' "+ data.rows[0].id +" ', NULL, ' "+ Factoryname +" ', ' Insert new data ', now ()); ";            query (SQL); Res.json ({message: ' Insert data successfully!        ‘}); }). catch (function (err) {Console.log (err);});});

  

The feeling of using promise:

1. Do not handle the error in each callback function, just need to deal with it in the last one, of course, you can deal with the place you want to deal with.

2, Avoid callback hell, layers of nested look at their own disgusting.

Operation MySQL in node. js using Promise

Related Article

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.