var fs = require('fs')
fs.writeFile('./test.txt','hello world',function (err) {
if (err) {
return 0
}
console.log('hello') /* 输出hello */
fs.readFile('./test.txt','utf-8', function (err,data) {
console.log(data) /* 输出hello world */
})
})
刚接触异步和回调函数的概念,有点晕,readfile是异步方法,
请问readfile里面的代码是等console.log('hello')执行完再执行还是和他同步执行的?
hellow world有没有可能输出在hello之前呢?
请问readfile里面的代码是等console.log('hello')执行完再执行还是和他同步执行的?
答:同步执行,hello,运行完在到readfile
要让hello在之前输出,写在readfile回调里面,hello world下面。
var fs = require('fs')
fs.writeFile('./test.txt','hello world',function (err) {
if (err) {
return 0
}
fs.readFile('./test.txt','utf-8', function (err,data) {
console.log(data) /* 输出hello world */
console.log('hello') /* 输出hello */
})
})
###这是用的回调
###console.log('hello')
同readFile
是同步的;先执行console
,在执行readFile
,如果在readFile
执行完才需要执行console
,需要将console.log('hello')
写在readFile
的回调里面