亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

javascript - Async/Await報錯

瀏覽:86日期:2023-09-02 08:25:08

問題描述

這段代碼問題在哪,一運行就報錯

var sleep = async function(para) {return new Promise(function(resolve, reject) { setTimeout(function() {resolve(para * para) }, 1000)}) } var errorSleep =async function(para) {return new Promise(function(resolve, reject) { setTimeout(function() {reject(’ ErrorSleep’) }, 1000)}) } try {var result1 = await sleep(1);var result2 = await errorSleep(4);var result3 = await sleep(1);console.log(’result1: ’, result1)console.log(’result2: ’, result2)console.log(’result3: ’, result3) } catch (err) {console.log(’err: ’, err)console.log(’result1: ’, result1)console.log(’result2: ’, result2)console.log(’result3: ’, result3) }

javascript - Async/Await報錯

問題解答

回答1:

await 只能在 async 包裝的函數里面用。就和yield只能在generator函數里面用一樣。

回答2:

樓上不是說了嗎,丟到async函數里。

var sleep = async function(para) {return new Promise(function(resolve, reject) { setTimeout(function() {resolve(para * para) }, 1000)}) } var errorSleep =async function(para) {return new Promise(function(resolve, reject) { setTimeout(function() {reject(’ ErrorSleep’) }, 1000)}) }//一樣丟到async函數里 var af = async function() {try { var result1 = await sleep(1); var result2 = await errorSleep(4); var result3 = await sleep(1); console.log(’result1: ’, result1) console.log(’result2: ’, result2) console.log(’result3: ’, result3)} catch (err) { console.log(’err: ’, err) console.log(’result1: ’, result1) console.log(’result2: ’, result2) console.log(’result3: ’, result3)} } af();回答3:

await 只能在 async 函數(函數,函數表達式,箭頭函數) 中使用,所以你只需要寫個 async 函數把那段代碼包起來就好了,我比較喜歡寫 main 函數而不是直接在全局作用域內運行

async function main() { try {var result1 = await sleep(1);var result2 = await errorSleep(4);var result3 = await sleep(1);console.log('result1: ', result1);console.log('result2: ', result2);console.log('result3: ', result3); } catch (err) {console.log('err: ', err);console.log('result1: ', result1);console.log('result2: ', result2);console.log('result3: ', result3); }}// 記得調用main();

另外也可以使用 async IIFE 表達式,比如

// IIFE 函數表達式(async function() { // todo main process})();// IIFE Lambda 表達式(箭頭函數表達式)(async () => { // todo main process})();

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 丰满老妇猛交视频 | 亚洲精品久久精品h成人 | 日本无卡无吗中文免费 | 精品热线九九精品视频 | 久久日韩精品 | 国产乱码一区二区三区四川人 | 精品精品久久宅男的天堂 | 91精品欧美一区二区三区 | 黄片毛片在线观看 | 毛片大全| 香蕉视频在线观看黄 | 国产一二三区在线 | 国产亚洲精品美女久久久 | 在线观看国产一区亚洲bd | 久久99精品久久久久久欧洲站 | 国产人成精品午夜在线观看 | 国产黄色片免费看 | 国产亚洲女在线精品 | 久久久线视频 | 日韩性视频网站 | 在线看片 在线播放 | 99精品久久秒播无毒不卡 | 日韩欧美在线第一页 | 手机看片欧美日韩 | 亚洲综合在线一区 | 久草手机在线观看视频 | 精品国精品自拍自在线 | 国内一区| 国产手机在线αⅴ片无码观看 | 乡下女色又黄一级毛片 | 特级淫片aaaa毛片aa视频 | 久久精品国产免费一区 | 日日麻批免费视频 | 911国产在线观看精品 | 美女黄视频大全 | 青青自拍视频一区二区三区 | 最新国产成人综合在线观看 | 国产日产欧产美一二三区 | 色综合中文字幕 | 日本特黄特黄刺激大片免费 | 欧美激情精品久久久久久大尺度 |