-1

EDITED: adjusted my narrative, and attempted to add output to code as examples show but it doesn't work. What am I doing wrong?

Hi experts or enthusiast superior to myself,

The question is "how to properly get the output from a asynchronous function in node.js as a return". The examples all talk of this mysterious callback function but in the context of my code I don't see how it applies or gets implemented.

Yes, the question has been asked many times, if I had to ask it again it is because the explanations provided didn't get this newb to a understanding. Yes, I spent near 24 hours or so trying to follow the examples, documentation, and other posts, but I didn't find one that explained it clear enough that I could apply to my code.

The concept of asynchronous makes sense, the code runs but the, in this case, https call hasn't. The code doesn't wait for the https call. You have to somehow grab the result after it has completed. While I haven't found the practicality of it, I am sure I will as I continue to learn why node.js is special in this way. Assuming my understanding is mostly right, my question is still the same. Concept is one thing, application and syntax are another.

This seems to be a common question and something nearly everyone new has trouble with.

Thus far none of the examples or explanations seem to clarify where or how with what I am working with. I understand there are additional modules that handle these differently but I believe I wont understand the 'why/how' as it applies unless I figure this out properly.

As I am brand new to node.js feel free to expand on any aspect of my code as I am eager to learn.

If anyone is finding this, this code will get data from the official Clash Royal API for which you require to register your IP and get a token from https://developer.clashroyale.com.

app.js

require('dotenv').config();
var func = require('./functions.js');

console.log(func.uChests(process.env.MyPlayer));  //this should output the value

functions.js

require('dotenv').config();
//console.log('Loaded Functions')
module.exports.uChests = func_uChests

//Clearly wrong application
//function func_uChests (playerID) {
function func_uChests (playerID,output) {
    //console.log('uChests')
    var http = require("https");

    var options = {
      "method": "GET",
      "hostname": "api.clashroyale.com",
      "port": null,
      "path": "/v1/players/%23"+ playerID + "/upcomingchests",
      "headers": {
        "content-length": "0",
        "authorization": "Bearer " + process.env.Token,
        "accept": "application/json"
      }
    };

    var req = http.request(options, function (res) {
      var chunks = [];

      res.on("data", function (chunk) {
        chunks.push(chunk);
      });

      res.on("end", function () {
        var body = Buffer.concat(chunks);
        console.log(body.toString());

        /*  example output
        {"items":[{"index":0,"name":"Magical Chest"},{"index":1,"name":"Silver Chest"},{"index":2,"name":"Silver Chest"},{"index":3,"name":"Golden Chest"},{"index":4,"name":"Silver Chest"},{"index":5,"name":"Silver Chest"},{"index":6,"name":"Silver Chest"},{"index":7,"name":"Golden Chest"},{"index":8,"name":"Silver Chest"},{"index":22,"name":"Legendary Chest"},{"index":40,"name":"Giant Chest"},{"index":76,"name":"Super Magical Chest"},{"index":77,"name":"Epic Chest"}]}
{"items":[{"index":0,"name":"Magical Chest"},{"index":1,"name":"Silver Chest"},{"index":2,"name":"Silver Chest"},{"index":3,"name":"Golden Chest"},{"index":4,"name":"Silver Chest"},{"index":5,"name":"Silver Chest"},{"index":6,"name":"Silver Chest"},{"index":7,"name":"Golden Chest"},{"index":8,"name":"Silver Chest"},{"index":22,"name":"Legendary Chest"},{"index":40,"name":"Giant Chest"},{"index":76,"name":"Super Magical Chest"},{"index":77,"name":"Epic Chest"}]}
*/
      });
    });

    req.end();
  }

//Clearly wrong application
function uChests(input, output) {
    func_uChests(input, output);   
    console.log(output);
};
Maramor
  • 43
  • 1
  • 8
  • 2
    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) – Dave Newton Dec 02 '18 at 22:30
  • Correct this is a duplicate of many other similar questions but I don't get it. – Maramor Dec 02 '18 at 23:37
  • “I don’t get it" isn’t actionable: what don’t you get? There are tons of tutorials that explain async programming in JS: without knowing what the cognitive disconnect is it’s impossible to help beyond what’s already been shown in the tutorials—noting that SO isn’t a tutorial site. – Dave Newton Dec 03 '18 at 00:39
  • I do apologies that I haven't/can't articulate what I don't understand about how to apply the needed changes. If I understood better than I do then I probably wouldn't be asking for help. I will try and adjust my question to clarify. Thank you for pointing out that it isn't clear enough. – Maramor Dec 03 '18 at 06:23
  • It doesn't "wait" because there's nothing telling it to. You can either pass a function that's called in your "end" handler (a callback function), or resolve a promise in your end handler. (At least those are the typical options; you could also emit an event etc.) But these are discussed in all the async tutorials. Which tutorials have you tried to use? – Dave Newton Dec 03 '18 at 11:52
  • I am going to abandon node.js for the time being and dig up another language much easier. Thank you Dave Newton for at least attempting to help. I am now nearing 48 hours of following every search result I could find trying to figure this out. I don't have the time to waste learning a basic concept that I can do in any other language from the start. All I want is to store the result into a variable so I can use it. – Maramor Dec 04 '18 at 02:44

1 Answers1

-1

i think you should understand better na async nature of node , the only way you can return values to the caller statement is using a function parameter or Async/Await with Promises API,take a look below.

´ // return from a function parameter

myAsyncFunction(function(value){

console.log(value) })

// or using the Promise API let value = await myAsyncFunction()´

  • What is "value", I have tried with body.tostring() and it doesn't work. This is in part what I am so lost on. – Maramor Dec 02 '18 at 23:39
  • @Maramor "value" is whatever is passed to the function. – Dave Newton Dec 03 '18 at 00:37
  • :) ok I know how functions work but in my code I input playerID but I don't want playerID as the return and I fail to see how your example explains the question. As you pointed out in your comments above my question isn't clear enough so I will attempt to clarify. Thank you both for taking the time. – Maramor Dec 03 '18 at 06:31