Google News
logo
ml5.js - Interview Questions
How to Using Callbacks?
In p5.js, callbacks are passed as arguments to functions that often perform some asynchronous operation. For example, p5.js defines the loadJSON() function as the following:
loadJSON('http//example.com/data.json', (results) => {
  // Do something with the results
});
 
Notice that the results from the callback in p5.js are given as the only argument to the function. There is no error argument in the callback.
 
ml5.js, on the other hand, uses a pattern referred to as an error-first callback :
 
With this pattern, a callback function is passed to the method as an argument. When the operation either completes or an error is raised, the callback function is called with the Error object (if any) passed as the first argument. If no error was raised, the first argument will be passed as null. Taken from the Node.js documentation
 
For example if you are using the imageClassifier() method, you will need to construct it in the following way:
// Pass a callback function to constructor
const classifier = ml5.imageClassifier('MobileNet', (err, model) => {
  console.log('Model Loaded!');
});

// Make a prediction with the selected image and pass a callback function with two arguments
classifier.predict(image, (err, results) => {
  // Check for errors. If no errors, then do something with the results
});
 
Error first callbacks is a convention common to many JavaScript libraries that we have chosen to adopt. The language JavaScript itself does not enforce this pattern. Keep in mind that most ml5.js methods and functions are asynchronous (machine learning models can take significant amounts of time to process inputs and generate outputs!). You will need to use the error-first callback pattern if you want to use callbacks.
Advertisement