Bdfy
Bdfy

Reputation: 24621

How to use "this" in async function?

I have simple example:

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() ...

I want to add file contents in this.text variable. How to do it ?

Upvotes: 2

Views: 170

Answers (3)

Nayjest
Nayjest

Reputation: 1089

  • Create local variable and store there 'this'

    read: function() { var _file = this; fs.readFile(this.name, function (err, data) { ... _file.text = data; ... }); },

  • Bind 'this' to inner function: read: function() {

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

    },

Note: It's insufficiently to store data to this.text: if you read something asynchronously in yur class, you need to provide callbacks to let other objects know that you got some data in yourFile.text

Upvotes: 5

Michelle Tilley
Michelle Tilley

Reputation: 159105

There's a couple things you can do:

  1. Create a scoped version of this:

    File.prototype = {
      read: function() {
        var self = this;
        fs.readFile(this.name, function (err, data) {
          self.text += data;
        });
      }
    };
    
  2. Bind the function to the current value of this:

    File.prototype = {
      read: function() {
        fs.readFile(this.name, function (err, data) {
          this.text += data;
        }.bind(this));
      }
    };
    

Upvotes: 0

jli
jli

Reputation: 6623

You could save a reference to this outside the closure and reference it from within:

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

Upvotes: 4

Related Questions