javascript中的 async与await
一、async 函数概述
1. async 函数的定义
async 函数是 JavaScript 中用来处理异步操作的一种声明方式,它的出现极大地简化了异步代码的编写。通过在函数前加上 async 关键字,我们可以将这个函数定义为异步函数,并允许在函数内部使用 await 来暂停函数的执行,等待异步操作完成。
1 async function fetchData() { 2 let response = await fetch('https://api.example.com/data'); 3 let data = await response.json(); 4 return data; 5 }
2、async 函数的返回值
一个 async 函数始终返回一个 Promise 对象。即使函数内部返回的是一个普通值,该值也会被包装成 Promise,因此我们可以通过 .then() 方法来处理返回结果,或者使用 await 来获取返回值。
1 async function example() { 2 return 'Hello, async!'; 3 } 4 5 // 使用 then() 处理返回值 6 example().then(value => console.log(value)); // 输出:Hello, async! 7 8 // 或者使用 await 处理返回值 9 (async () => { 10 let result = await example(); 11 console.log(result); // 输出:Hello, async! 12 })();
3. 异常处理
async 函数内部抛出的异常会被自动封装到返回的 Promise 中。因此,我们可以通过 .catch() 或者 try...catch 语句来捕获这些异常。
1 async function fetchData() { 2 try { 3 let response = await fetch('https://api.example.com/data'); 4 let data = await response.json(); 5 return data; 6 } catch (error) { 7 console.error('Error fetching data:', error); 8 } 9 }
二:await 关键字详解
1. await 的作用
await 关键字只能在 async 函数中使用,它的作用是暂停 async 函数的执行,等待一个 Promise 对象的结果。在 Promise 被 resolve 后,await 表达式会返回 Promise 的结果。如果 Promise 被 reject,则 await 会抛出异常。
async function getResult() {
let result = await someAsyncFunction();
console.log(result);
}
2. await 的执行顺序
在 await 等待 Promise 结果的过程中,JavaScript 的事件循环会继续执行其他任务,而不会阻塞整个程序。仅当 Promise 完成后,async 函数才会继续往下执行。这种机制保证了程序的高效性。
1 async function example() { 2 console.log('Start'); 3 await new Promise(resolve => setTimeout(resolve, 2000)); 4 console.log('End'); 5 } 6 7 example(); 8 console.log('Running...');
在上述代码中,Start 和 Running... 会立即输出,而 End 会在两秒后输出。
案例01:
1 <script> 2 function executeAsync(){ 3 setTimeout(()=>{ 4 console.log("执行完毕executeAsync"); 5 },30000); 6 return 122; 7 } 8 async function execute(){ 9 let result = await executeAsync(); 10 console.log("result:"+result); 11 return "execute执行完成"; 12 } 13 let _execute = execute(); 14 _execute.then((data)=>{ 15 console.log("data:"+data); 16 }); 17 console.log("_execute:",_execute); 18 </script>
执行结果:
_execute: Promise {<pending>}
result:122
data:execute执行完成
执行完毕executeAsync
案例02:
1 <script> 2 function executePromise(){ 3 let promise=new Promise((resolve)=>{ 4 setTimeout(()=>{ 5 console.log("执行完毕executePromise_Log"); 6 resolve("执行完毕executePromise"); 7 },10000); 8 }); 9 return promise; 10 } 11 async function execute(){ 12 let result = await executePromise(); 13 console.log("result:"+result); 14 return "execute执行完成"; 15 } 16 let _execute = execute(); 17 _execute.then((data)=>{ 18 console.log("data:"+data); 19 }); 20 console.log("_execute:",_execute); 21 </script>
执行结果:
_execute: Promise {<pending>}
执行完毕executePromise_Log
result:执行完毕executePromise
data:execute执行完成
浙公网安备 33010602011771号