0

So I am not sure how to convert a function that I have that is built synchronously but uses asynchronous calls.

do_thing = () => {
  var N = new Thing(); //sync

  N.do_that();        // calls fs.readFile() and does some stuff with data  :async
  this.array.push(N); // sync but does not affect anything
  this.save();        // calls fs.writeFile() but needs info from N that is not created yet as N.do_that() is not done
}

I am not sure how to make it so when N.do_that() is done it then calls this.save(). I do not want to use fs.readFileSync() or fs.writeFileSync(). I would like to know how to something like:

N.do_that().then( this.save() );
Drew
  • 1,171
  • 4
  • 21
  • 36

2 Answers2

0

Ok I figured it out. Inside my N.do_that(); I added a callback, something like so:

do_that = (callback) => {
  fs.readFile("file", (err, fd) => {
    // do stuff with fd

    callback();
    return;

  });
}

then rather than calling :

N.do_that();
array.push(N);
this.save();

I did

N.do_that(() => {
  array.push(N);
  this.save();
};
Drew
  • 1,171
  • 4
  • 21
  • 36
0

You could use a 3rd-party, open source tool that already gives you Promisified versions to help! One Google search revealed: https://www.npmjs.com/package/fs-promise

Otherwise, you can promisify the method yourself using tips from https://stackoverflow.com/a/34642827/3814251.

(Alternatively, use callbacks, which you've posted in your own answer.)

Community
  • 1
  • 1
therobinkim
  • 2,500
  • 14
  • 20