国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

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

javascript - Async/Await報錯

瀏覽:116日期: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
相關文章:
主站蜘蛛池模板: 芦溪县| 同德县| 武功县| 柯坪县| 察隅县| 凤城市| 乐昌市| 吉林省| 柘城县| 那坡县| 宝清县| 洪洞县| 长宁区| 安国市| 体育| 丰镇市| 北宁市| 宜州市| 芦溪县| 陇西县| 武穴市| 舞钢市| 东光县| 沁水县| 习水县| 乌恰县| 克什克腾旗| 剑阁县| 永城市| 新乡县| 南岸区| 台南市| 阜南县| 濮阳市| 唐海县| 平武县| 葫芦岛市| 银川市| 凤凰县| 杨浦区| 石狮市|