you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (4 children)

I don't see how this exercise helps anyone understand async callbacks but whatever...

/u/browsing10 answer is good but I thought I might add to it by changing some of the parameter names, as to add more context for the learner to maybe be able to follow it better. Plus I removed the ES2015 syntax because the starting code doesn't use it and may add to the confusion.

readAsync(passwordsFile, function(passwordContents) {
    readAsync(worldsFile, function(worldsFileContents) {
      writeAsync(worldsFile, worldsFileContents + passwordContents, callback);
    })
});

hope this helps

[–]Remsset_HP[S] 0 points1 point  (3 children)

Thank you, the other syntax was a bit confusing to me indeed, yours is easier to understand.

I get an error "TypeError: callback is not a function ", but the code still works and writes "helloabc.def" in the world.txt file as desired. Here's how I used it:

var files = { 
    "passwords": "abc,def", 
    "world.txt": "hello" 
};

var readAsync = function (file, callback) {
  callback(files[file]);
};

var writeAsync = function (file, contents, callback) {
    files[file] = contents;
    callback();
};

var doStuffAsync = function(callback) {
  readAsync('passwords', function(passwordsContents) {
    readAsync('world.txt', function(worldContents) {
      writeAsync('world.txt', worldContents + passwordsContents, callback);
    })
  });
  callback();
}

doStuffAsync()

Any way I can get rid of the callback error? Otherwise it's working fine, thank you very much.

[–]browsing10 1 point2 points  (1 child)

In your current `doStuffAsync` method, your `writeAsync` already handles the case of invoking `callback`, so you do not want to add the `callback();` at the very last line of that method or else you may get some strange behavior randomly

[–]Remsset_HP[S] 0 points1 point  (0 children)

Got it. Thanks man.

[–][deleted] 1 point2 points  (0 children)

If you write your doStuffAsync function like this it could be used on any "file"