javascript - Async/Await報錯
高洛峰
高洛峰 2017-06-17 09:15:45
0
3
924

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

    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)
    }
    
    

#
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回覆(3)
三叔

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

为情所困

樓上不是說了嗎,丟到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();
黄舟

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
})();
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板