ES6中async函數(shù)與await表達式的基本用法舉例
一、async 函數(shù)
概念:
async 是一個修飾符,async 定義的函數(shù)會默認的返回一個Promise對象resolve(成功值)的值,因此對async函數(shù)可以直接進行then操作,返回的值即為then方法的傳入函數(shù)。
舉例:
async function demo(){ // 1:當返回值不是promise對象 當調用函數(shù)的時候就是已成功的值 // return "succ"; // 2:當返回的是promise對象 那么函數(shù)(promise對象)的結果與返回的promise狀態(tài)一致 return new Promise((resolve,reject)=>{ //Promise 內(nèi)容請參考上期作品,關注專欄。 let flag = true; if(flag){ resolve("succ"); }else{ reject("error"); } }) } const MyPromise = demo(); MyPromise.then((resolve)=>{ console.log(resolve); },(reject)=>{ console.log(reject); })
二、await表達式
它也是一個修飾符,await 關鍵字 只能放在 async 函數(shù)內(nèi)部, await關鍵字的作用 就是獲取 Promise中返回的內(nèi)容, 獲取的是Promise函數(shù)中resolve。
1.await必須放在async函數(shù)中
2.await右側的表達式一般為promise對象
3.await可以返回的是右側promise成功的值
4.await右側的promise如果失敗了,就會拋出異常,需要通過try…catch捕獲處理
舉例:
// 1:await需要寫在async函數(shù)的內(nèi)部 // 2:await 修飾的Promise 返回的值就是resolve的值 // 3:后面的代碼需要等待 await后的結果 async function demo(){ const a = await "a"; const b = await new Promise((resolve,reject)=>{ setTimeout(()=>{ console.log("定時器執(zhí)行了...."); resolve("b"); },3000); }); const c = await "c"; console.log(a,b,c); } demo();
舉例:失敗的代碼 await 錯誤的代碼 需要用try catch捕獲
async function demo(){ try{ const a = await new Promise((relsolve,reject)=>{ reject("數(shù)據(jù)不存在"); }) }catch(error){ console.log(error); } } demo();
三、async await ajax 基礎使用
function mark (url){ return new Promise((resolve,reject)=>{ const ajax = new XMLHttpRequest(); ajax.open("GET",url) ajax.send(); ajax.onreadystatechange=function(){ if(ajax.readyState==4){ if(ajax.status==200){ resolve(JSON.parse(ajax.response)); } } } }) } async function demo(){ const res = await mark("http://127.0.0.1:5500/test.json")
補充:async await ajax使用
首先要創(chuàng)建對象,用get的方法請求后面?zhèn)魅氲牡刂?,再發(fā)送請求,通過判斷出輸出有無數(shù)據(jù)。
function sendajax(url){ return new Promise((resolve,reject)=>{ const http = new XMLHttpRequest();//創(chuàng)建對象 http.open("GET",url);//用get方法請求地址 http.send();//發(fā)送請求 http.onreadystatechange = function(){ if(http.readyState==4){ if(http.status==200){ resolve(JSON.parse(http.response)); } } } }) } async function demo(){ const res = await sendajax("http://127.0.0.1:8848/web2209/ES6/test.json"); if(res.code==200){ console.log("有數(shù)據(jù)"); }else{ console.log("無數(shù)據(jù)"); } } demo();
總結
到此這篇關于ES6中async函數(shù)與await表達式的基本用法的文章就介紹到這了,更多相關ES6 async函數(shù)與await表達式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解ES6數(shù)組方法find()、findIndex()的總結
這篇文章主要介紹了詳解ES6數(shù)組方法find()、findIndex()的總結,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05layui 對table中的數(shù)據(jù)進行轉義的實例
今天小編就為大家分享一篇layui 對table中的數(shù)據(jù)進行轉義的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09bootstrap datepicker限定可選時間范圍實現(xiàn)方法
這篇文章主要介紹了bootstrap datepicker限定可選時間范圍的實現(xiàn)方法,本文涉及到相關知識點,通過實例給大家介紹的非常詳細,需要的朋友可以參考下2016-09-09