问一个的nodejs的问题!

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之前呢?

阅读 2.4k
3 个回答

请问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的回调里面

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题