Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

问一个的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之前呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

请问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 */
    })
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share

1.2m questions

2.1m answers

5 comments

56.5k users

...