前端那些事--async/await

基本用法
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');
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值