87,989
社区成员
发帖
与我相关
我的任务
分享
fs.readFile('file1.txt', 'utf8', function (err, data) {
if (err) throw err;
console.log('File 被读取' + data);
});
nodejs基本上都是异步回调来处理业务
其实只要看几个后端代码或者自己写几个,就会对回调有比较深的理解了,不需要说学回调还需要专门看一本书
function doSomething(callback) {
callback('stuff', 'goes', 'here');
console.log('a')
}
function foo(a, b, c) {
console.log(a + " " + b + " " + c);
}
doSomething(foo);
我的理解是不应该先打印出a,之后在打印出stuff', 'goes', 'here吗[/quote]
不哦,因为你callback是先执行的哦,在doSomething这个函数里,都是同步操作,所以是按顺序从上向下执行的。
function doSomething(callback) {
setTimeout(function(){
callback('stuff', 'goes', 'here');
})
console.log('a')
}
function foo(a, b, c) {
console.log(a + " " + b + " " + c);
}
doSomething(foo);
加个setTimeout模拟异步操作,就是先打印a再打印其他的。 function doSomething(callback) {
callback('stuff', 'goes', 'here');
console.log('a')
}
function foo(a, b, c) {
console.log(a + " " + b + " " + c);
}
doSomething(foo);
我的理解是不应该先打印出a,之后在打印出stuff', 'goes', 'here吗