0

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);
  }
};
therobinkim
  • 2,500
  • 14
  • 20
Hendry Lim
  • 1,929
  • 2
  • 21
  • 45
  • I don't think you're doing anything wrong with this piece of code given that the documentation says `yolo.detect()` returns a Promise if no callback is provided. I'm curious though -- what if you `console.log(err)` in Pattern 1? Does your code output errors there? – therobinkim May 04 '19 at 00:45
  • @therobinkim, thanks. if i include in console.log(err), it still works fine // Detect objects in the video element yolo.detect(function(err, results) { if (results) { console.log(results); } else { console.log(err); } }); – Hendry Lim May 04 '19 at 01:44

0 Answers0