await/async代替 回调函数 解决回调地狱

1)回调函数法

function parseJsonStrToObj(str, callback) {
    setTimeout(function () {
        try {
            var obj = JSON.parse(str);
            callback(null, obj);
        } catch (e) {
            callback(e, null);
        }
    }, 0);
}

parseJsonStrToObj('{ "obj": 1 }', function (err, data) {
    if(err){
        console.log("失败", err);
        return;
    }
    console.log("成功", data);
});

parseJsonStrToObj({ "obj": 1 }, function (err, data) {
    if (err) {
        console.log("失败", err);
        return;
    }
    console.log("成功", data);
});

/*
$ node app2.js
成功 { obj: 1 }
失败 SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse ()
    at Timeout._onTimeout (C:\Users\Administrator\Desktop\test-node\app2.js:4:28)
    at ontimeout (timers.js:427:11)
    at tryOnTimeout (timers.js:289:5)
    at listOnTimeout (timers.js:252:5)
    at Timer.processTimers (timers.js:212:10)
*/

造成回调地狱,同时,2个异步函数的执行,不知道执行顺序,因此,不推荐

2)await/async

async function parseJsonStrToObj(str) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            try {
                var obj = JSON.parse(str);
                resolve(obj);
            } catch (e) {
                resolve({});
            }
        }, 3000);
    });
}

async function main() {
    console.time("start");

    var ret = await parseJsonStrToObj({ "obj": 1 });
    console.log("ret=", ret);

    ret = await parseJsonStrToObj('{ "obj": 1 }');

    console.log("ret=", ret);
    console.timeEnd("start");
}

main();

/*
$ node app3.js
ret= {}
ret= { obj: 1 }
start: 6021.451ms
*/

 

你可能感兴趣的:(node.js)