JavaScript中async,await的使用和方法
function hellworld() { return '您好!美好世界!';}console.log(hellworld()); // 您好!美好世界!async function asyHellworld() { return '您好!美好世界!';}console.log(asyHellworld()); // Promise { ’您好!美好世界!’ }
普通函數 hellworld 將簡單地返回字符串 您好!美好世界! ,而 async 函數將返回 Promise 對象。
如果需要使用異步函數返回的值,則需要在它后面添加 .then() 程序塊,如下:
async function asyHellworld() { return '您好!美好世界!';}asyHellworld().then((str) => console.log(str)); // 您好!美好世界!
await 關鍵字將確保異步函數的 Promise 將在繼續執行其它可能需要等待值的代碼之前完成并返回結果。
async function asyHellworld() { return await Promise.resolve('您好!美好世界!');}asyHellworld().then(console.log); // 您好!美好世界!
這段代碼雖然簡單,但確實顯示了 await 關鍵字的用法,以及它應該如何在函數體中使用 Promise 對象。
接下來為了讓代碼更容易理解,去掉代碼中的 Promise 語法,如下:
async function asyHellworld() { return '您好!美好世界!';}async function printHello() { const strHello = await asyHellworld(); console.log(strHello);}printHello();
上面這段代碼可以更加直觀的看清楚 async 和 await 的使用。通常 async 和 await 是用來處理異步操作,是把異步變為同步的一種方法。
async 聲明一個 function 來表示這個異步函數,await 用于等待函數中某個異步操作執行完成。
通過上面的介紹,對 async 和 await 有一個初步的認識,那么能用來做什么呢?
await 關鍵字將確保異步函數的 Promise 將在繼續執行其它可能需要等待值的代碼之前完成并返回結果。
因此,在處理AJAX異步請求的時候,如在VUE項目中,通常處理的方式如下:
login(username, password).then((loginResult) => { // 登錄請求發出后的處理請求 console.log('登錄成功!');});
而使用 await 就可以這樣來處理:
const loginResult = await login(username, password);console.log(loginResult);
這里需要注意一點,await 要在異步函數中才能使用,上面代碼是有問題,假如是在 store 里面處理的話,就需要改成:
const actions = { async [LOGIN]({ commit }, payload) {const { username, password } = payload;const loginResult = await login(username, password);console.log(loginResult); },};
在這里可以看出,對于要處理由多個 Promise 組成的 then 鏈的時候,優勢就能體現出來了。
還有一個常用的用途,是實現程序的暫停,即 sleep 方法,實現代碼如下:
const sleep = (ms) => { return new Promise((resolve) => setTimeout(resolve, ms));};(async () => { console.log('開始執行,10秒打印你好'); await sleep(10 * 1000); console.log('你好');})();
到此這篇關于JavaScript中async,await的使用和方法的文章就介紹到這了,更多相關Js async和await 內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!