1

I'm trying to solve a JavaScript challenge where I have to use asynchronous callbacks.

Here is what the challenge says:

Define a function named doStuffAsync that takes one argument callback. Your function should read the contents of file "passwords", write the result to file "world.txt" along with the extra text "OWNED", then call callback with no arguments. Use both the asynchronous readAsync and asynchronous writeAsync.

My code is as follows:

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 test = function() {
    files["out.txt"] = "final";
    files["passwords"] = "blank";
};

//this is the part I'm interested in
var doStuffAsync = function (callback) {
    var contents = 0;   
    contents = readAsync("passwords");
    writeAsync("world.txt", contents, callback());
};

Here is the link to the challenge http://nathansjslessons.appspot.com/lesson?id=1085

4
  • @enapupe Why mention jQuery? It's not relevant. Commented May 20, 2014 at 16:32
  • What exactly is your question? Do you not understand the post and its examples? Have you noticed any way in which your snippet differs from those examples? Commented May 20, 2014 at 16:38
  • Please note that SO questions are usually expected to contain a question somewhere. I don't see one in your post. Commented May 20, 2014 at 16:38
  • The code under "this is the part I'm interested in" is written by me. The question was how do I solve what I need to solve given that the code that I have written doesn't do that. Commented May 20, 2014 at 16:59

1 Answer 1

3

The most straightforward way to accomplish this using just callbacks is by nesting the function calls like this:

function doStuffAsync(callback) {
    readAsync("passwords", function(contents) {
        writeAsync("world.txt", contents + "OWNED", function() {
            callback();
        });  
    });
}

In this case, since your callback function doesn't require any arguments, you can save one level of nesting and just do this:

function doStuffAsync(callback) {
    readAsync("passwords", function(contents) {
        writeAsync("world.txt", contents + "OWNED", callback);  
    });
}

This isn't so bad with just two callback actions, but it can quickly get pretty messy when you need to perform a lot of asynchronous steps in sequence. Promises are one mechanism that were devised to help manage this problem, and I recommend checking them out.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.