0

I can't understand why a callback is not using lexical scoping with javascript. Can anyone explain this to me?

is this library forcing me to put all my code in a callback? https://www.npmjs.com/package/base64-img

My test code:

Note: I didn't include the setup code to run the server and middleware errorHandler, because I felt that would take too long and be overbearing on this question.

const base64Img = require('base64-img');

router.get('/url_to_base64', async (req, res, next) => {
  try {
    const url = 'https://i.imgur.com/6gMn1RD.png';
    let base64;
    base64Img.requestBase64(url, function (err, result, body) { // callback()
      console.log('BODY', body.slice(0, 30));
      base64 = body.slice(0, 30);
      console.log('base64_inside_cb', body.slice(0, 30));
    });
    console.log('base64_outside_cb', typeof base64);
    res.send({ message: 'success' });
  } catch (err) {
    next(err);
  }
});

expected output:

base64_outside_cb string
GET /tests/url_to_base64 200 8.599 ms - 21
BODY data:image/png;base64,iVBORw0K
base64_inside_cb data:image/png;base64,iVBORw0K

actual output:

base64_outside_cb undefined
GET /tests/url_to_base64 200 8.599 ms - 21
BODY data:image/png;base64,iVBORw0K
base64_inside_cb data:image/png;base64,iVBORw0K

anyone know how I can capture that string base64_outside_cb outside of the callback?

Fiddle Freak
  • 1,923
  • 5
  • 43
  • 83
  • in your base64Img.requestBase64(url, function (err, result, body) { // callback() line, shouldn't be base64Img.requestBase64(url, function (err, res, body) { ? Where is that 'result' coming from? – mindmaster Feb 20 '19 at 21:31
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Robin Zigmond Feb 20 '19 at 21:38
  • @MiguelCruz I renamed the result, because it was a conflict where res.send() wasn't working from the function prior to the callback. – Fiddle Freak Feb 20 '19 at 21:49

0 Answers0