0

I am new to NodeJS and JavaScript. I am badly stuck in a problem: I want to generate QR image of 'some text' and after generating it, I want to query my MySQL database and insert the image to database. Problem is that QRCode.toDataURL of SOLDAIR module goes in running state and query is called before the QR image is returned from the .toDataUrl function. Hence it results in error.

I tried everything, promises, nested promises, counters, if statements etc., but I am unable to find a solution.

My code:

router.post('/generateTicket', (req,res) => {
  const query1 = `SELECT * FROM booking ORDER BY  bookingID DESC LIMIT 1`;
  const query2 = `INSERT INTO ticket (ticket_image,BookingID) SET ?`;
  let bookingID;
  let count;
  let ticket_data = {};
  Promise.using(mysql.getSqlConn(), conn => {
    conn.query(query1).then(resultOfQuery1 => {
      bookingID = resultOfQuery1[0].BookingID;
      count = resultOfQuery1[0].PeopleCount;

      console.log("ID = " + bookingID + " people count = "+count);

      promiseToCreateQRcode().then(function (URLfromResolve) {
        console.log("the url is " + URLfromResolve );
      }).catch(function (fromReject) {
        console.log("Rejected "+ fromReject);
      }); // catch of promise to create QR

    }).catch(err => {
      res.json({ status: 500, message: 'Error Occured in query 1 ' + err });
    }); // catch of query 1
  });
});


var opts = {
  errorCorrectionLevel: 'H',
  type: 'image/png',
  rendererOpts: {
    quality: 0.3
  }
};

let promiseToCreateQRcode = function () {
  let QRImage;
  return new Promise(function (resolve,reject) {
    QRCode.toDataURL('text', function (err, url) {
    if (err) throw err
      console.log("\n"+url+"\n");
      QRImage = url;
    });

    if (QRImage)
      resolve(QRImage);
    else
      reject("error occured in url");
  });
};

As u can see, the program jumps to if statement and the QR image is not generated yet, hence it goes in "reject":

image

Maak
  • 4,720
  • 3
  • 28
  • 39

2 Answers2

0

Try this,

let promiseToCreateQRcode = function () {
return new Promise(function (resolve,reject) {
    QRCode.toDataURL('text', function (err, url) {
        if (err){
          reject(err); // or some message
        } else {
           resolve(url);
      }
    });
  });
};

This way promise will be resolved only when toDataURL returns QR image.

Satish Kumar
  • 601
  • 6
  • 14
0

Have a look at How do I convert an existing callback API to promises?. You need to call resolve or reject in the asynchronous callback!

function promiseToCreateQRcode() {
    return new Promise(function(resolve,reject) {
        QRCode.toDataURL('text', function (err, url) {
            if (err) {
                reject(err);
            } else {
                console.log("\n"+url+"\n");
                resolve(url);
            }
        });
    });
}

Using this extra QRImage variable like you did cannot work.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375