У меня проблема в проекте Node.js. У меня есть код, который проходит через весь список JSON и печатает "1", а также у меня есть код, который использует API и печатает "2". Сейчас программа печатает:
2
1
и я хочу, чтобы программа печатала:
1
2
Мой код:
//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);
});
}
Что мне нужно сделать?
Вам нужно вызвать функцию apigClient.invokeApi
в конце tabletojson.convertUrl
функции tabletojson.convertUrl
.
Вот так:
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');
}
Это называется обратным вызовом: https://en.wikipedia.org/wiki/Callback_(computer_programming)