Reputation: 524
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
Upvotes: 1
Views: 759
Reputation: 101768
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.
Upvotes: 3