09-Node.js学习笔记-异步编程

同步API,异步API

同步API:只有当前API执行完成后,才能继续执行下一个API

console.log('before');
console.log('after');

异步API:当前API的执行不会阻塞后续代码的执行

console.log('before');
setTimeout(function(){
    console.log('last')
},2000)
console.log('after');

同步API,异步API的区别(获取返回值)

同步API可以从返回值中拿到API执行的结果,但是异步API不可以的

回调函数

自己定义函数让别人去调用

function getData(callback){
    callback()
}
getData(function(){
    console.log('callback函数被调用了')
})
function getData(callback){
    callback('糖糖糖')
}
getData(function(n){
    console.log('callback函数被调用了')
    console.log(n)
})
function getMsg(callback){
    setTimeout(function(){
        callback({
            msg:'hello node.js'
        })
    },2000)
}
getMsg(function(data){
    console.log(data)
})

猜你喜欢

转载自www.cnblogs.com/foreverLuckyStar/p/12072683.html