I am using a 3rd party library ml5 that has a function that returns a callback function. Using Pattern 1 works fine but Pattern 2 failed with error "pixels passed to tf.fromPixels() cannot be null".

I like to use the async / await pattern so that my code is more easily readable. Anyone knows how to achieve make the code works with async/await

Pattern 1

handleDetect = async snap => {
  const yolo = await ml5.YOLO(snap);

  yolo.detect(function(err, results) {
    console.log(results); 
  });
};

Pattern 2

handleDetect = async snap => {
  const yolo = await ml5.YOLO(snap);

  try {
    const results = await yolo.detect();
    console.log(results);
  } catch (error) {
    throw new Error(error);
  }
};

0 Answers