async/await 使用的注意事项

在用async/await时,我遇到了一个错误:

(node:7340) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: 全完了
(node:7340) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

错误代码如下:

function hh(bool) {
    return new Promise((resolve,reject)=>{
        setTimeout(function () {
            if(bool) {
                resolve("ok");
            } else {
                reject(new Error("全完了"));
            }
        },1000)
    })
}
async function test(bool) {
    return await hh(bool);
}

console.log(test(false));

而且返回test函数的处理结果是一个promise对象,而不是预期的字符串或错误对象。后来查询了相关资料,才明白标注了async的函数会成为一个异步函数,返回promise对象。而且对于promise对象抛出的错误是要处理一下的,不然就会报上面的错误,修改后结果如下:

function hh(bool) {
    return new Promise((resolve,reject)=>{
        setTimeout(function () {
            if(bool) {
                resolve("ok");
            } else {
                reject(new Error("全完了"));
            }
        },1000)
    })
}
async function test(bool) {
    try {
        console.log(await hh(bool));
    } catch(err) {
        console.error(err)
    }

}

test(false);

现在就很正常了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容