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?