基本用法
async/await 是es7引入的新语法,可以更加方便的进行异步操作
async 关键在用在函数上 (async 函数的返回值是promise实例对象)
await 关键字用在async 函数当中(await 可以得到异步结果)
async function GetData(){
// 注:await 可以是promise 实例对象
let data = await axios.get('/axios');
return data;
}
GetData().then(ret=>{
console.log(ret);
})
async function GetDatas(){
let ResData = await new Promise(function(reslove,reject){
reslove('hello world')
});
return ResData;
}
GetDatas().then(ret=>{
console.log(ret);
})
处理多个异步请求
async function QueryData(){
let one = await axios.get('one');
let two = await axios.get('two?info='+one.data);
return two;
}
QueryData().then(data=>{
console.loe(data);
})
node.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extend:false}));
app.use(bodyParser.json());
// 允许CORS
app.all('*',(req,res,next)=>{
res.header('Access-Control-Allow-Origin','*');
res.header('Access-Control-Allow-Methods','get,post,put,delete,options');
res.header('Access-Control-Allow-Headers','X-Requested-With');
res.header('Access-Control-Allow-Headers','Content-Type');
res.header('Access-Control-Allow-Headers','mytoken');
next();
})
app.get('/one',(req,res)=>{
res.send('world');
});
app.get('two',(req,res)=>{
if(req.query.info=='world'){
res.send('ok');
}else{
res.send('error')';
}
})
app.listen(3000,function(){
console.log('server running at http://127.0.0.1:3000');
})