javascript的async/await
用async/await处理异步
- async就是代表异步的意思 ,此代码不会阻止后边代码的执行。用法:只需要在函数前面加上acync,则表示此函数是个异步函数。
async function getUsers(username){
let sql = `select * from user where username = '${username}'`;
let result = await exc(sql);
return result;
}
比如此段代码的含义就是声明getUsers(username)方法是个异步的方法。
调用方法跟普通方法一样,直接调用,不过不同点就是此函数不会阻塞下面代码的执行。例如以下代码:
async function hello(){
return "hello";
}
hello();
console.log('world');
而控制台输出只有world,却没有输出hello,这是因为async函数返回值是个promise对象。让我们来输出写下以下代码console.log(hello());
控制台输出为 Promise { 'hello' }
原因很简单,async函数的返回值是promise对象,获得promise的值就必须采then方法。所以
async function hello(){
return "hello";
}
hello().then(data=>{
console.log(data);
}).catch(err=>{
console.log(err);
})
console.log('world');
这样就输出了
而async通常和await一起使用。await就是等待的意思,他等他后面跟随的表达式执行完毕之后再执行其他代码。而需要注意的是await通常是在async函数里面。通常await后面跟随promise函数,等拿到结果后继续往下执行。
function sum (num){
return new Promise((resolve, reject) =>{
setTimeout(()=>{
resolve(num+10);
},2000);
})
}
async function hello(){
let result = await sum(10);
let result2 = await sum(20);
let result3 = await sum(30);
return result+ result2 + result3;
}
hello().then(data=>{
console.log(data);
})
最终在六秒之后拿到了结果。