1

I have a problem in my Node.js project. I have some code that goes through an entire list of JSON and prints "1", and also I have some code that is using API and prints "2". Right now the program prints:

2

1

and I want that the program to print:

1

2

My code:

//include libraries
const apigClientFactory = require('aws-api-gateway-client');
const tabletojson = require('tabletojson');
const Promise = require('promise');
//Global variables

const url = '****';
var jsonOutput = {};

//////////////////////1/////////////////////////
//Convert Html tables to Json object
tabletojson.convertUrl(url, function(tablesAsJson) {
    var exchangeJson = tablesAsJson[0];
    console.log("1");
    var j = 0;
    for(var i = 0 ;i < exchangeJson.length; i++)
    {
        jsonOutput[j++] =
            {
                ****
            };
    }
    
});

//////////////////////2/////////////////////////
var apigClient = apigClientFactory.default.newClient({
    accessKey: '****',
    secretKey: '****',
    invokeUrl: '****'
});


var pathTemplate = '/staging/rates';
var method = 'POST';
console.log("2");
for (var i = 0; i < jsonOutput.length; i++) {
    var body = {
                currency: jsonOutput[i].currency,
                chain: '****',
                buy: parseFloat(jsonOutput[i].buy),
                sell: parseFloat(jsonOutput[i].sell)
            };

apigClient.invokeApi({city: '****', country: '****'}, pathTemplate, method, {}, body)
    .then(function (result) {
        console.log(JSON.stringify(result.data));
    }).catch(function (result) {
        console.log(result);
    });
}

What do I need to do?

Nirmalsinh Rathod
  • 5,079
  • 4
  • 26
  • 56
DD apps
  • 57
  • 1
  • 6
  • 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) – peteb Aug 01 '17 at 19:35
  • ever heard about async.parallel https://www.npmjs.com/package/async-parallel , https://caolan.github.io/async/docs.html#parallel – wrangler Aug 01 '17 at 19:48
  • Node.js is asynchronous so you need to call the new task inside a callback if you care about order of execution. Either that or you can use `async` module. – spicypumpkin Aug 01 '17 at 20:41

1 Answers1

0

You need to invoke the apigClient.invokeApi function at the end of your tabletojson.convertUrl function call.

Like so:

tabletojson.convertUrl(url, function(tablesAsJson) {
var exchangeJson = tablesAsJson[0];
console.log("1");
var j = 0;
for(var i = 0 ;i < exchangeJson.length; i++)
{
  jsonOutput[j++] =
  {
    ****
  };
}

function2({city: '****', country: '****'}, ...);

});


function2 (args) {
  console.log('2');
}

That is called a callback: https://en.wikipedia.org/wiki/Callback_(computer_programming)

Cherna
  • 58
  • 6