Node.js异步API返回值的处理

Node.js里面异步API的返回结果的处理

我们在Node.js中对异步API的返回结果不能直接用return来接受,而实用回调函数来接受。代码如下

function getMsg(callback) {
    setTimeout(function () {
        message = {
            msg: 'hello nodejs'
        }
        callback(message)
    }, 2000)

}
getMsg(function (obj) {
    console.log(obj);
})

如果直接返回值的话就是:

function getMsg() {
    setTimeout(function () {
        return {
            msg: 'hello nodejs'
        }

    }, 2000)

}
const msg = getMsg();
console.log(msg);

以上两种代码msg的返回值不同:第一种情况在这里插入图片描述

第二种情况:在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/coucouxie/article/details/107524280