#How can I get a variable out of a nested function's local variables?

11 messages · Page 1 of 1 (latest)

boreal osprey
#

How would I go about using the value of username in other parts of my code? I've tried declaring it outside of the functions, but it didn't work. I've read that people used Callbacks do make something like this work, but I couldn't figure it out.

const https = require('https')
//const fs = require('fs')

function uuidCheck(req) {
    var uuid = req.params.uuid // in url
    https.get("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid, uuidToUsername)
    function uuidToUsername (res) {
        var body = ""
    
        res.on("data", (chunk) => {
            body += chunk
        })
    
        res.on("end", jsonStuff)

        function jsonStuff () {
            var username = JSON.parse(body).name;
            console.log(`Found ${username}`)
            //grab username variable to use in other parts of code
        }
    }
}

module.exports = {uuidCheck}
#

How can I get a variable out of a nested function's local variables?

candid igloo
#

In callback based approach, you would have to pass username to another callback (most likely passed as an argument to uuidCheck (next to req param). However, modern code handles async stuff with promises, so you may transform your code to use it:

function uuidCheck(req) {
    var uuid = req.params.uuid // in url

    return new Promise(resolve => {
      https.get("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid, uuidToUsername)
        function uuidToUsername (res) {
            var body = ""
    
            res.on("data", (chunk) => {
                body += chunk
            })
    
            res.on("end", jsonStuff)

            function jsonStuff () {
              var username = JSON.parse(body).name;
              console.log(`Found ${username}`)  
              //grab username variable to use in other parts of code
              resolve(username); // `return` to caller
          }
      }
    })
}

module.exports = {uuidCheck}

// caller
const username = await uuidCheck(req);
#

If you just need to fetch some data from other server, then you should use fetch or other high level HTTP API (like axios). Using Node's https is tedious.

const fetch = require('fetch'); // or `require('node-fetch')` for older Node

function uuidCheck(req) {
  var uuid = req.params.uuid // in url

  return fetch("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid, uuidToUsername)
    .then(res => res.json())
    .then(({ name: username }) => username);
}

module.exports = { uuidCheck }
boreal osprey
#

thanks!

boreal osprey
# candid igloo In callback based approach, you would have to pass `username` to another callbac...

promises do not like me... I got this error TypeError: Cannot read properties of undefined (reading 'then')

const fetch = require('fetch');


function uuidCheck(req) {
    var uuid = req.params.uuid; // in url

    console.log(`UUID: ${uuid}`);

    return fetch.fetchUrl("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid, callbackInfo)
        .then(res => res.json()) //error happens on this line
        .then(({ name: username }) => username);
}

function callbackInfo() {
    console.log('callback');
}

module.exports = {uuidCheck};```
#

this is the code calling the function initially js async uuid() { app.get('/uuid/:uuid', function (req, res) { UUIDtoUsername.uuidCheck(req); res.end(); }) }

#

Some sites say that the error would occur because no promise is returned, but that isn't the case here.

boreal osprey
#

I have figured it all out

candid igloo
#

Why fetch.fetchUrl instead of just fetch?

boreal osprey