Node.js 回调函数实例详解
Node.js回调函数阻塞与非阻塞
node.js异步编程的直接体现就是回调。
异步编程依托于回调来实现,但不能说使用了回调后程序就异步化了。
回调函数在完成任务后就会被调用,Node使用了大量的回调函数,Node所有API都支持回调函数。
阻塞代码实例(同步函数)
//阻塞是按顺序执行的
varfs=require("fs");
vardata=fs.readFileSync('input.txt');
console.log(data.toString());
console.log("程序执行结束!");
非阻塞实例(异步函数)
//非阻塞是不需要按顺序的
varfs=require("fs")
fs.readFileSync('ipnut.txt',function(err,data){
if(err)returnconsole.log(err)
console.log(data.toString())
})
console.log("程序执行结束!");
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!