JavaScript async/await 详解之初学指南
     
  
      
      
     
    
      
        如果你曾经陷入回调地狱或对 Promises 感到沮丧,那么 JavaScript 的 async/await 可以帮你解决!这是一种处理异步代码的现代方法,易于理解,适合初学者,并且让你的代码看起来干净美观。
让我们通过一个简单的真实示例深入研究,即使是初学者也可以理解!
什么是 async/await? 
将 async/await 视为编写异步代码(如从服务器获取数据)的更好方法。
async:这个神奇的词告诉 JavaScript,“嘿,这个函数将执行一些异步操作!” 
await:这个关键字的意思是,“在这里等待异步任务完成,然后继续。”
它们一起帮助你编写看起来同步(一步一步)但异步运行的代码。
你为什么要关心? 
开发人员喜欢 async/await 的原因如下:
不再有回调地狱:你的代码看起来不再像嵌套回调的乱七八糟。 
更轻松地调试:使用 try...catch 可以更轻松地跟踪和修复错误。 
干净的代码:异步代码变得像你最喜欢的小说一样易读。 
 
让我们看一个现实生活中的例子
想象一下:你正在构建一个天气应用。你需要:
获取用户详细信息 。 
根据用户的个人资料查找用户的位置 。 
获取该位置的天气更新 。 
 
以下是我们如何使用 async/await 实现此目的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 const  fetchUserData  = ( ) => {    return  new  Promise ((resolve ) =>  {         setTimeout (             () =>  resolve ({ id : 1 , name : "Alice" , locationId : 202  }),             1000          );     }); }; const  fetchLocationData  = (locationId ) => {    return  new  Promise ((resolve ) =>  {         setTimeout (             () =>  resolve ({ locationId, city : "Paris" , country : "France"  }),             1000          );     }); }; const  fetchWeatherData  = (city ) => {    return  new  Promise ((resolve ) =>  {         setTimeout (             () =>  resolve ({ city, temperature : "18°C" , condition : "Cloudy"  }),             1000          );     }); }; async  function  getWeatherUpdates ( ) {    try  {         console .log ("Fetching user details..." );         const  user = await  fetchUserData ();         console .log ("User fetched:" , user);         console .log ("Fetching location details..." );         const  location = await  fetchLocationData (user.locationId );         console .log ("Location fetched:" , location);         console .log ("Fetching weather data..." );         const  weather = await  fetchWeatherData (location.city );         console .log ("Weather fetched:" , weather);         console .log (             `Hi ${user.name} ! 🌟 The weather in ${location.city}  is ${weather.temperature}  and ${weather.condition} .`          );     } catch  (error) {         console .error ("Oops! Something went wrong 🛑:" , error);     } } getWeatherUpdates ();
 
初学者分解 
模拟 API 调用: 
 
每个函数(如 fetchUserData)都使用 Promises 模拟 API 请求。这就是应用程序与服务器通信的方式!
分步流程: 
 
await 关键字在每个步骤中暂停函数,直到 Promise 解析。这使得代码易于阅读——就像遵循食谱一样!
错误处理: 
 
try...catch 块确保即使出现问题,你也可以优雅地处理错误。
初学者专业提示 
想让你的应用运行得更快吗?无需等待任务逐一完成,而是使用 Promise.all 同时运行独立任务:
1 2 3 4 5 6 7 async  function  fetchParallel ( ) {    const  [user, location] = await  Promise .all ([         fetchUserData (),         fetchLocationData (202 ),     ]);     console .log ("Data fetched in parallel:" , user, location); } 
 
为什么 async/await 会改变游戏规则? 
以下是前后对比:
❌ async/await 之前(回调地狱):
1 2 3 4 5 6 7 fetchUserData ((user ) =>  {    fetchLocationData (user.locationId , (location ) =>  {         fetchWeatherData (location.city , (weather ) =>  {             console .log (weather);         });     }); }); 
 
✅ async/await 之后:
1 2 3 4 5 6 async  function  getWeather ( ) {    const  user = await  fetchUserData ();     const  location = await  fetchLocationData (user.locationId );     const  weather = await  fetchWeatherData (location.city );     console .log (weather); } 
 
你更愿意写哪一个?
总结 
async/await 是每个 JavaScript 开发人员工具包中必备的工具。它简化了异步编程,使你的代码看起来更简洁、工作得更好、感觉更流畅。
      
     
    
      
  
 
  
    
      
      
        
        致力于网站建设与Web开发。喜欢新事物,关注前后端动态,对新的技术有追求, 做一个优秀的web全栈工程师。