asyncawait 使用说明

    技术2023-03-25  84

    scync/await 说明 // async 是异步函数,不会阻塞其他代码运行, async function f() { return "hello async" } const fn = f(); console.log(fn); // 你会发现它是一个promise 对象 fn.then(res=>{ console.log(res) }) console.log('虽然在后面,但是我先执行'); await // 模拟请求后台,俩秒后执行 function doubleA(num) { let flang = true // 主要演示,报错后通过try catch 来捕获异常 return new Promise((resolve, reject) => { setTimeout(() => { if(flang){ resolve(2 * num) }else { reject('出错了~~') } }, 2000); } ) } async function testResult() { // console.log(1) // let result = await doubleA(30); // await 是等待这个函数执行完毕返有回值,后继续执行下面的代码 如果没有加 await 就拿不带异步值 // console.log(2) // console.log(result); let first,second,third try { first = await doubleA(30); second = await doubleA(50); third = await doubleA (30); }catch (e) { console.log(e) } console.log(first + second + third); // 你会发现6秒后输出值 就像写同步代码一样,没有回调的感觉,非常舒服。 } testResult();
    Processed: 0.010, SQL: 9