Home  >  Article  >  Web Front-end  >  What is the usage of nodejs then

What is the usage of nodejs then

藏色散人
藏色散人Original
2021-10-20 14:28:313327browse

Usage of nodejs then: 1. Install the mysql module under nodejs; 2. Introduce js through the "require()" method; 3. Through "Mysql.updateMysql(Name,Path).then(... )" method just use then.

What is the usage of nodejs then

The operating environment of this article: windows7 system, nodejs version 10.16.2, Dell G3 computer.

The use of .then in nodejs

How do we use .then to return the result set in nodejs

1. Install the mysql module under nodejs

npm install mysql

2. Here is the configuration and function of our Mysql.js

//引入数据库
var mysql=require('mysql');
//实现127.0.0.1本地链接
var DATABASE = "test";
var table='test'
var connection = mysql.createConnection({
    host:'127.0.0.1',
    user:'root',
    password:'root',
    port:'3306',
    database: DATABASE
});

//修改数据
function  updateMysqlToken(Id,Name,Path) {
    console.info('select Name====' + Name);
    console.info('select Path====' + Path);
    var Name = Name;
    var Path = Path;
//主要是这里对Promise的使用,只有Promise才能使用.then
    return new Promise(function (resolve,reject){
        //定义我们的sql
        var updateSql = 'UPDATE ' + table +' set Name = ?, Path = ?, 
        where Id = ? ';
        //这里对应sql的字段
        var updateParams = [Name,Path,Id];
        //nodejs的执行
        connection.query(updateSql,updateParams, function(err, rows, fields ) {
            if (err){
                reject(err)
            }
            // console.log(  `The solution is: ${rows.length }  `  );
            console.info(` the getRowByPkOne sql ${updateSql}`)
            if( !rows || rows.length == 0 )
                resolve(null)
            else
                resolve(rows[0])
        })
    })
}

3. Write our .then usage below. Res.send returns data in JSON format

//引入js,这里是对数据库的连接配置
var Mysql = require('Mysql.js'); 

Mysql.updateMysql(Name,Path).then(
                    //updateMysql修改这里返回的值是个object对象,所以我们需要对其进行JSON解析
                    function(message) {
                        console.info('message===' + JSON.stringify(message));
                    }
                )
                //将结果集返回给前端
                res.send(result);
            }

Recommended learning: "node.js video tutorial"

The above is the detailed content of What is the usage of nodejs then. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn