Node.js
Callback
Learn native callbacks and async.
Callback
A callback is a function passed as a parameter to another function and called later. Native addons use callbacks to respond to JS. callWithCallback(value, cb) models this: it calls cb(value) and returns the result.
Example: callWithCallback(5, (v) => v * 2). Here (v) => v * 2 is the callback; it is called with 5 and returns 10. In a native addon a callback is called when a long job finishes, so JS is not blocked while waiting. Here we use a synchronous model but the structure is the same: take a value and a callback, call the callback with the value, return the result. The output is 10, the callback's return value.
The callback call
In this lesson we write the callWithCallback function. The function takes a value and a callback; it calls the callback with the value and returns the result. This shows how native addons respond to JS with a simple model.
Example: function callWithCallback(value, cb) { return cb(value); }. callWithCallback(5, (v) => v * 2) returns 10. The cb(value) call runs the callback; its return value becomes the function's return. On the native side this is done with napi_call_function; here we use a direct JS call. console.log(callWithCallback(5, (v) => v * 2)) prints 10. This is the most basic form of the callback pattern.
Exercise Write the callback function
Write function callWithCallback(value, cb). Call the callback with return cb(value). Print console.log(callWithCallback(5, (v) => v * 2)).
Show example solution
function callWithCallback(value, cb) {
return cb(value);
}
console.log(callWithCallback(5, (v) => v * 2));
Test yourself
-
What does callWithCallback(5, (v) => v * 2) return?
callWithCallback(5, (v) => v * 2)
Show answer
10 — The right answer is: 10. The callback is called with 5, returning 5*2=10.
-
Complete the callback call
function callWithCallback(value, cb) { return ____(value); }
Show answer
function callWithCallback(value, cb) { return cb(value); }
-
Match each concept to its description
- Callback
- A function called later
- cb(value)
- Calls the callback with a value
- (v) => v * 2
- An arrow function
- return
- Returns the result
Next lesson: Build