0

I've recently started learning javascript, specifically node.js, and am having trouble in the program I am writing.

Basically I need to make an HTTP request and then set a variable based on the response.

The problem seems to be when my node.js program sends a response the variable is blank. Here is the code for the HTTP request:


function search(productCategory, productId) {

  var options = {
        "method": "GET",
        "hostname": 'HOSTNAME',
        "path": [
            "PATH",
        ],
        "headers": {
            "x-api-key": "API_KEY",

        }
    };


    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);


            var result = JSON.parse(body);

           var id = result.result[0].value;

            // console.log(id);
            return req.id;
        });
    });

     req.end();
}

console.log correctly outputs the desired value.

The function that calls this one looks something like this:



module.exports = function getId(req, res) {

    var categoryId = "";
    var productId = '';
    var posId = "";

    for(var i=0; i < req.body.result[0].products.length; i++){

        categoryId = req.body.result[0].products[i].category_id;
        productId = req.body.result[0].products[i].product_id;
        posId = search(categoryId, productId);

        var product = {
            "product number": i,
            "product_category": categoryId,
            "product_id": productId,
            "posId": posId
        };

        productsArray.push(product);


    }

    res.send(JSON.stringify(orderingProducts));


};

The goal is to send a response with an array of objects with the key posId gotten from the search method.

Thanks for the help!

Jonathan Zier
  • 150
  • 2
  • 14
  • Does this answer your question? [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) – jonrsharpe Aug 20 '20 at 21:18
  • I've looked through this and am still trying to apply it to my code here – Jonathan Zier Aug 20 '20 at 21:28

3 Answers3

2

Ok, there is multiple ways to do this. You can use async/await and promises for that. You can read about them on the web - it's pretty easy. Here is draft example:

function search(productCategory, productId) {
  // Here you return new promise
  return new Promise((resolve, reject) => {

  // Here you do your code and after it completes - resolve result
  var options = {
        "method": "GET",
        "hostname": 'HOSTNAME',
        "path": [
            "PATH",
        ],
        "headers": {
            "x-api-key": "API_KEY",

        }
    };


    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);
            var result = JSON.parse(body);
            var id = result.result[0].value;

            // console.log(id);
      
            //
            // Here you RESOLVE promise result
            resolve(id);
        });
    });

     req.end();

  });
}

And in caller function you modify it to be async and add await before calling promise function

// Add async before function to handle await method
module.exports = async getId(req, res) {

    var categoryId = "";
    var productId = '';
    var posId = "";

    for(var i=0; i < req.body.result[0].products.length; i++){

        categoryId = req.body.result[0].products[i].category_id;
        productId = req.body.result[0].products[i].product_id;
        // Add await to PAUSE execution of this function and wait
        // the result from search promise
        posId = await search(categoryId, productId);

        var product = {
            "product number": i,
            "product_category": categoryId,
            "product_id": productId,
            "posId": posId
        };

        productsArray.push(product);


    }

    res.send(JSON.stringify(orderingProducts));


};
tarkh
  • 2,424
  • 1
  • 9
  • 12
0

I think search function you are using to get postId is asynchronous and you need to handle it via async/await if this is at all returning promise.

only change, I made in below snippet is made function async and used await before search call so it wait until we get id.

module.exports = async function getId(req, res) {

var categoryId = "";
var productId = '';
var posId = "";

for(var i=0; i < req.body.result[0].products.length; i++){

    categoryId = req.body.result[0].products[i].category_id;
    productId = req.body.result[0].products[i].product_id;
    posId = await search(categoryId, productId);

    var product = {
        "product number": i,
        "product_category": categoryId,
        "product_id": productId,
        "posId": posId
    };

    productsArray.push(product);


}

res.send(JSON.stringify(orderingProducts));


};
0

fun1();

async function fun1() {
  let a = await new Promise((resolve, reject) => {
    fun2(resolve, reject);
  });
  console.log(a);
}

function fun2(resolve, reject) {
  // do something asychronous
  if (true) {
    resolve(1);
  } else {
    reject(2);
  }
}
Sachin Chillal
  • 393
  • 4
  • 6