Eric Funk
Eric Funk

Reputation: 49

How to make an API response become a global variable to use again in subsequent API request

Here is the code

request.post({
    headers: {"content-type": "application/x-www-form-urlencoded"},
    url: "https://testardor.jelurida.com/nxt?",
    form: 
        {requestType: "sendMoney"}
    },
    function (error, response, body) {
        if (!error && response.statusCode == 200){
            var transactionBytes = JSON.parse(response.body).transactionBytes;
        }
    },
);

I would like to take transactionBytes and pass it into another API request after this. How do I make it a global variable? I tried global.transactionBytes and window.transactionBytes and that didn't work. I have also read that is bad to declare a global variable like this, is there a better way to do this?

Upvotes: 0

Views: 1625

Answers (1)

Venkat Reddy
Venkat Reddy

Reputation: 1052

If it is just one file you can declare global variable just declaring out side of your function.

var globalvariable = 0;

function ApiCall() {
request.post({
    headers: {"content-type": "application/x-www-form-urlencoded"},
    url: "https://testardor.jelurida.com/nxt?",
    form: 
        {requestType: "sendMoney"}
    },
    function (error, response, body) {
        if (!error && response.statusCode == 200){
            var transactionBytes = JSON.parse(response.body).transactionBytes;
        }
    },
);
}

if you want to use same global variable in multiple files, you can create a helper file example

help.js

var globalVariable = 0;
module.exports = globalVariable

firstfile.js

var globalVariable = require('./help');
   function ApiCall() {
    request.post({
        headers: {"content-type": "application/x-www-form-urlencoded"},
        url: "https://testardor.jelurida.com/nxt?",
        form: 
            {requestType: "sendMoney"}
        },
        function (error, response, body) {
            if (!error && response.statusCode == 200){
                var transactionBytes = JSON.parse(response.body).transactionBytes;
                globalVariable = transactionBytes;
            }
        },
    );
    }

anotherfile.js

var globalVariable = require('./help');
function someotherthing() {
  console.log(globalVariable)
}

Using a global variable is bad unless really required, other way is just passing the value to next function. Global variable can cause memory leaks if not used properly

Upvotes: 1

Related Questions