async await 异步的简单用法
async 是声明一个异步函数,如 async ()=>{}
await 是等待一个异步方法执行,await 执行函数必须出现在 async 内部。如
async function test(){
let result = await new Promise.resolve('123456');
console.log(result); //123456
}
test();
简单的应用:
const test = function(params){ //参数
return new Promise((resolve, reject) => {
....执行方法
resolve(result) //结果通过resolve的方式返回
reject(err) //错误通过reject的方式抛出
});
}
async demo () => {
let result = await test(params); //result接收返回的处理结果
}
demo() //执行函数
async await 链接数据库:(cnpm install mysql --S)
var mysql = require('mysql');
var pool = mysql.createPool({
host:'127.0.0.1',
user:'root',
password:'',
port:'3306',
database:''
});
var query = function(sql, values){
return new Promise((resolve, reject) => {
pool.getConection(function(err, connection){
connection.query(sql, function(err, rows){
if(err){
reject(err);
}
resolve(rows);
})
});
});
}
async function demo(){
let sql = "select 1+1";
let result = await query(sql);
console.log(result); // 2
}
demo();
//exports.default = query;
async await 在koa2.x 路由中的简单应用:(cnpm install koa-router --S/yarn add koa-router)
const Router = require('koa-router');
const routers = new Router();
const query = require('./mysql.js');
routers.get('/', async (ctx, next) => {
var sql = "select 1+1";
let result = await query(sql);
console.log(result);
})
app.use(routers.routes()).use(routes.allowedMethods());
app.listen(3000, ()=>{
console.log('server port 3000 is runing');
});