【问题标题】:Calling codes after another was finished node.js一个接一个地调用代码 node.js
【发布时间】:2017-08-01 19:28:18
【问题描述】:

我的 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);
    });
}

我需要做什么?

【问题讨论】:

标签: javascript json node.js function


【解决方案1】:

您需要在tabletojson.convertUrl 函数调用结束时调用apigClient.invokeApi 函数。

像这样:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    相关资源
    最近更新 更多