Node.js 回调函数实例详解

Node.js 回调函数 阻塞与非阻塞

node.js 异步编程的直接体现就是回调。

异步编程依托于回调来实现,但不能说使用了回调后程序就异步化了。

回调函数在完成任务后就会被调用,Node 使用了大量的回调函数,Node 所有 API 都支持回调函数。

阻塞代码实例(同步函数)

//阻塞是按顺序执行的
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("程序执行结束!");

非阻塞实例(异步函数)

//非阻塞是不需要按顺序的
var fs = require("fs")
fs.readFileSync('ipnut.txt',function(err,data){
  if(err) return console.log(err)
  console.log(data.toString())
})
console.log("程序执行结束!");

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

你可能感兴趣的:(Node.js 回调函数实例详解)