Node.js异步编程(一)

1. 同步API, 异步API

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

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

2. 同步API, 异步API的区别

2.1 获取返回值不同

  • 同步API可以从返回值中拿到API执行的结果, 但是异步API是不可以的
// 同步
function sum (n1, n2) {
	return n1 + n2
}
const result = sum (n1, n2)
console.log(result)
// 异步
function getMsg () {
	setTimeout(function () {
		return { msg: 'hello Node.js' }
	}, 2000)
}
const msg = getMsg() // 返回undefined

通过回调函数获取异步API的值
回调函数: 自己定义函数让别人去调用。

function getMsg (callback) {
	setTimeout(() => {
    callback({
      msg: 'hello node.js'
    })
  }, 2000)
}

getMsg(data => {
  console.log(data)
})

结果:
在这里插入图片描述

2.2 代码执行顺序不同

  • 同步API从上到下一次执行, 前面代码会阻塞后面代码的执行
  • 异步API不会等待API执行完成后再向下执行代码
console.log('代码开始执行')

setTimeout(function () {
  console.log('2s')
}, 2000)

setTimeout(() => {
  console.log('0s')
}, 0)

console.log('代码执行结束')

结果:
Node.js异步编程(一)_第1张图片

3. Node.js中的异步API

  • 文件读取
    fs.readFile('./demo.txt', (err, data) => {})
  • 事件监听, 事件处理函数就是回调函数
const server = http.createServer()
server.on('request', (req, res) => {})

你可能感兴趣的:(nodejs)