1

I am attempting to set a variable scannedCode to a scanned qr code result. However, the steps after that happens continues even before scannedCode is in use, due to the promises. How can I make it so nothing continues until the variable finishes and is usable?

function stuff(image) {
      var scannedCode = qrRun(image);
     console.log("I want to console.log scannedcode and it be the actual thing completed")
}

async function qrRun(image) {
  const img = await jimp.read(fs.readFileSync(image));
  const qr = new QRReader();
  const value = await new Promise((resolve, reject) => {
    qr.callback = (err, v) => err != null ? reject(err) : resolve(v);
    qr.decode(img.bitmap);
  });
  console.log(value.result);
  return value.result;
}

Or if there is no way to do that, how would I just remove the Promise from the function currently there so I don't need a .then without breaking the qrrun.

blueberrr
  • 63
  • 1
  • 7
  • 1
    You either need to make `stuff` async and await (if that makes sense for what needs to happen) or `.then` on `qrRun` or `scannedCode` to handle just the stuff that needs to wait. If anything *needs* to wait for `stuff`, you also would need to return a promise and `await` or `.then` there too. – crashmstr Dec 08 '22 at 20:41
  • Either `const scannedCode = await qrRun(image);` or `qrRun(image).then(scannedCode => { … });`. There's no way out, `stuff` is also asynchronous if it calls the asynchronous `qrRun` method. And no, there's no way to remove the promise. – Bergi Dec 09 '22 at 01:44

1 Answers1

0
async function stuff(image) {
  const scannedCode = await qrRun(image);
}
Evert
  • 93,428
  • 18
  • 118
  • 189