问答

问一个的nodejs的问题!

作者:admin 2021-07-06 我要评论

var fs = require('fs')fs.writeFile('./test.txt','hello world',function (err) { if (err) { return 0 } console.log('hello') /* 输出hello */ fs.readFile(...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)
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的回调里面

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • 问一个的nodejs的问题!

    问一个的nodejs的问题!

  • 如何利用swagger的yaml文件自动去更新

    如何利用swagger的yaml文件自动去更新

  • webkitdirectory实现web文件夹上传的问

    webkitdirectory实现web文件夹上传的问

  • URL编码和ASCII编码有没有关系?

    URL编码和ASCII编码有没有关系?

腾讯云代理商
海外云服务器