Skip to content Skip to sidebar Skip to footer

Passing A Variable To A Request-promise Function Inside A Foreach Loop

I am calling an API for price data which is working correctly. However, I am trying to pass the variable exchange_pair_id into the then() function. Inside the forEach loop the exch

Solution 1:

This happens due to the fact, that the function in the .then() is executed after the request-promise resolves, which takes some time. In the meanwhile the forEach-loop finishes and assigns the last asset to exchange_pair_id - which in your code is a global variable as a proper declaration is missing (see below)! After that the first request-promises begin to resolve and execute their callback, but at this time the forEach-loop is already finished so exchange_pair_id will always log the same value.

To avoid that exchange_pair_id is in the global scope, you should use a , instead of ; after var assets = asset['assets']; (second line). Or simply add another var in front of exchange_pair_id = asset['exchange_pair_id'];

response.forEach(function(asset) {
    var assets = asset['assets'], // <---- use ',' instead of ';'
        exchange_pair_id = asset['exchange_pair_id'];

    options.uri = exchange_objects[exchange[0]].ticker + '?pair=' + assets[0] + assets[1]; // overwrite to fit the request to Kraken APIconsole.log(exchange_pair_id) // uniquerp(options).then(function(response) {
        key = Object.keys(response['result']);
        price_data = response['result'][key];

        console.log(exchange_pair_id) // duplicate
    });                 
});
  1. Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)

Anyway I recommend you to use let in order to declare variables as it may sometimes prevent undesirable behaviour of your code. See the MDN docs on let to get to know what it does - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Solution 2:

Here you are experiencing an asynchronous problem.

When you execute the forEach you push tasks into the node.js to do list.

enter image description here

Then when you function stop, they get executed and access id.

enter image description here

Post a Comment for "Passing A Variable To A Request-promise Function Inside A Foreach Loop"