dw软件做网站,wordpress进入后台空白,教育网站建设 飞沐,wordpress 免登录发布一、async函数
async是一个加在函数前的修饰符#xff0c;被async定义的函数会默认返回一个Promise对象resolve的值。
因此对async函数可以直接then#xff0c;返回值就是then方法传入的函数。
// async基础语法
async function fun0(){console.log(1);return 1;
}
fun0()…一、async函数
async是一个加在函数前的修饰符被async定义的函数会默认返回一个Promise对象resolve的值。
因此对async函数可以直接then返回值就是then方法传入的函数。
// async基础语法
async function fun0(){console.log(1);return 1;
}
fun0().then(val{console.log(val) // 1,1
})async function fun1(){console.log(Promise);return new Promise(function(resolve,reject){resolve(Promise)})
}
fun1().then(val {console.log(val); // Promise Promise
}//声明一个async函数
async function main() {console.log(async function);//情况1返回非promise对象数据return hahaha;//情况2返回是promise对象数据/* return new Promise((resolve, reject) {// resolve(ok);reject(error);}) *///情况3抛出异常// throw new Error(出错啦!!!);
}
let result main().then(value {console.log(value);
});
console.log(result);二、await表达式
await 也是一个修饰符只能放在async定义的函数内。可以理解为等待。
await 修饰的如果是Promise对象可以获取Promise中返回的内容resolve或reject的参数且取到值后语
句才会往下执行如果不是Promise对象把这个非promise的东西当做await表达式的结果。
注意事项
await必须写在async函数中但是async函数中可以没有await如果await的promise失败了就会抛出异常需要通过try…catch捕获处理
async function fun(){let a await 1;let b await new Promise((resolve,reject){setTimeout(function(){resolve(setTimeout)},3000)})let c await function(){return function}()console.log(a,b,c)
}
fun(); // 3秒后输出 1 setTimeout functionfunction log(time){setTimeout(function(){console.log(time);return 1;},time)
}
async function fun(){let a await log(1000);let b await log(3000);let c log(2000);console.log(a);console.log(1)
}
fun();
// 立即输出 undefined 1
// 1秒后输出 1000
// 2秒后输出 2000
// 3秒后输出 3000async function main() {//1、如果await右侧为非promise类型数据var rs await 10;var rs await 1 1;var rs await 非常67;//2、如果await右侧为promise成功类型数据var rs await new Promise((resolve, reject) {resolve(success);})//3、如果await右侧为promise失败类型数据,需要借助于try...catch捕获try {var rs await new Promise((resolve, reject) {reject(error);})} catch (e) {console.log(e);}
}
main();// 使用async/await获取成功的结果// 定义一个异步函数3秒后才能获取到值(类似操作数据库)
function getSomeThing(){return new Promise((resolve,reject){setTimeout((){resolve(获取成功)},3000)})
}async function test(){let a await getSomeThing();console.log(a)
}
test(); // 3秒后输出获取成功案例async结合await读取文件内容
//1、导包
const fs require(fs);
const {promisify} require(util);
//2、将fs.readFile转化成promise风格的函数
const myreadfile promisify(fs.readFile);
//3、声明async函数
async function main(){try{//4、读取文件let one await myreadfile(./resource/4.html);let two await myreadfile(./resource/2.html);let three await myreadfile(./resource/3.html);//5、拼接读取文件内容console.log(one two three);}catch(e){console.log(e);}
}
//6、调用main函数
main();