0

QR code is generated but can't be logged to the console, when stored in a variable.

I was trying to generate qrcode in a node application but when I tried logging the console, it returned undefined. Kindly help me out with this issue. I am using qrcode package.

My code:

import QRCode from "qrcode";

let qrcode;

QRCode.toDataURL("I am a pony!")
  .then((url) => {
    qrcode = url;
  })
  .catch((err) => {
    console.error(err);
  });

console.log(qrcode);

It logged correctly when I put console.log(url) in the then statement.

  • 1
    Checkout [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). To get the data, the Promise should be resolved. – Shri Hari L Jun 22 '23 at 08:00

1 Answers1

-1

In your code, the promise is't resolved yet. I just tried to execute a function with await and the value of qrcode filled in correctly.

async testQR() {
    let qrcode;

    await QRCode.toDataURL('I am a pony!')
        .then((url) => {
          qrcode = url;
        })
        .catch((err) => {
          console.error(err);
        });

    console.log(qrcode); // data:image/png;base64,iVBORw0KGgoAAAA...
}