Node.js 同步与异步编程

同步API: 只有当前API执行完成之后,才能继续执行下一行API。从上往下,一行一行的执行。

console.log("one")

console.log("two")

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

 console.log("one")

setTimeout ( () =>  console.log("two"), 3000)

console.log("three")

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

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

// 同步

function sum (a, b) {
  return a+ b  
}
// 异步

function getMsg () {
  setTimeout( function () {
    console.log('hello node.js')  
  })   
}

异步API获取数据的方式(回调函数)

 1 function getMsg (fn) {
 2   setTimeout(function () {
 3     fn({
 4       msg: 'hello'
 5     })
 6   }, 3000)
 7 }
 8 
 9 getMsg(function (data) {
10   console.log(data)
11 })

猜你喜欢

转载自www.cnblogs.com/liea/p/11220711.html