gpt4 book ai didi

node.js - 如何在异步函数中使用 "this"?

转载 作者:搜寻专家 更新时间:2023-11-01 00:12:07 26 4
gpt4 key购买 nike

我有一个简单的例子:

function File(name) {
this.name = name
this.text = null
}

File.prototype = {
read: function() {
fs.readFile(this.name, function (err, data) {
}
},
getContent: function() {
return this.text
}
}

var myfile = new File('my_file')

watch.createMonitor('my_file_dir', function (monitor) {
monitor.files['my_file']
monitor.on("change", function (f, stat) {
myfile.read()
}
})

main program....:

myfile.getContent() ...

我想在 this.text 变量中添加文件内容。怎么做?

最佳答案

  • 创建局部变量并存储“this”

    阅读:函数(){ 变种_文件=这个; fs.readFile(this.name, function (err, data) { ... _file.text = 数据; ... });},

  • 将“this”绑定(bind)到内部函数:阅读:函数(){

     fs.readFile(this.name, function (err, data) {
    ...
    this.text = data;
    ...
    }.bind(this)

    },

注意:将数据存储到 this.text 是不够的:如果您在类中异步读取某些内容,则需要提供回调以让其他对象知道您在 file.text 中获得了一些数据

关于node.js - 如何在异步函数中使用 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10988135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com