CodeBlanks Logo Icon CodeBlanks

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.

Practice Write the callback function

Write function callWithCallback(value, cb). Call the callback with return cb(value). Print console.log(callWithCallback(5, (v) => v * 2)).

Starter code

index.js
// Write a callWithCallback function
// Takes a value and a callback
// Call the callback with the value, return the result
// Call with 5 and (v) => v * 2, print
// write here

Sample solution

index.js
function callWithCallback(value, cb) {
  return cb(value);
}
console.log(callWithCallback(5, (v) => v * 2));

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does callWithCallback(5, (v) => v * 2) return?

index.js
callWithCallback(5, (v) => v * 2)
  • 5
  • 2
  • 10 Correct answer
  • 7

Explanation: The right answer is: 10. The callback is called with 5, returning 5*2=10.

2 Complete the callback call

Question
function callWithCallback(value, cb) { return ____(value); }
Answer
function callWithCallback(value, cb) { return cb(value); }

Explanation: cb(value) calls the callback.

3 Match each concept to its description

Term Meaning
Callback A function called later
cb(value) Calls the callback with a value
(v) => v * 2 An arrow function
return Returns the result

All lessons in Expert