To kick things off, we'll make a fake async function using setTimeout to simulate a delay inside utils.js. Just below where we make our add function, let's make one called asyncAdd. It'll essentially have the same features, but it'll use setTimeout and it'll have a callback to simulate a delay. Now in the real world, this delay might be a database request or an HTTP request. We'll be dealing with that in the following chapters. For now though, let's add module.exports.asyncAdd:
module.exports.add = (a, b) => a + b;
module.exports.asyncAdd = ()
This will take three arguments, as opposed to the two the add function took, a, b, and callback:
module.exports.add = (a, b) => a + b;
module.exports.asyncAdd = (a, b, callback)
This is what's going to make the function asynchronous. Eventually, once the setTimeout is up, we'll call the callback with the sum, whether it's one plus three being four, or five plus nine being fourteen. Next up, we can put the arrow in arrow function (=>) and open and close our curly braces:
module.exports.asyncAdd = (a, b, callback) => {
};
Inside the arrow function (=>), as mentioned, we'll be using setTimeout to create the delay. We'll pass in a callback and we'll pass in our setTimeout. Let's go with 1 second in this case:
module.exports.asyncAdd = (a, b, callback) => {
setTimeout(() => {
}, 1000);
};
Now, by default, if our tests take longer than 2 seconds, Mocha will assume that is not what we wanted and it'll fail. That's why we're using 1 second in this case. Inside our callback, we can call the actual callback argument with the sum a + b, just like this:
module.exports.asyncAdd = (a, b, callback) => {
setTimeout(() => {
callback(a + b);
}, 1000);
};
We now have an asyncAdd function and we can start writing a test for it.