【问题标题】:For-loop order (with asynchronous function)For循环顺序(带异步功能)
【发布时间】:2017-12-19 15:11:14
【问题描述】:

我有这个代码:

exports.formatDepArrTables = function(jsonReturn, type, placeName, callback) {
    let toSend = "";

    if (type == 'departure') {
        for (let j = 0; j < jsonReturn.departures.length; j++) {
            console.log("DEPARTURES LOOP j = " + j + "/" + jsonReturn.departures.length);

            if(currentDeparture.display_informations.links[0] === undefined) {
                toSend += ""; // setting some string informations
            }
            else {
                let oceTrainId = ""; // random number given by a json
                _this.getDisruptionFromDisruptionId(oceTrainId, function(data) {
                    for(let i = 0; i < data.disruptions[0].impacted_objects[0].impacted_stops.length; i++) {
                        if(currentImpactedStop.stop_point.label == placeName) {
                            toSend += "string";
                        }
                    }
                });
            }
        }
        console.log("End of the first loop");
        return callback(toSend);

    } else if (type == 'arrival') {
        // copy&paste
    } else {
        throw new Error("not defined");
    }
};

当我运行这段代码(我使用 NodeJS)时,它从第一个循环中产生 1/10、2/10...,但它没有在第一个循环的第一次迭代中迭代第二个循环(并且它显示“第一个循环结束”并开始第二个循环)。

getDisruptionFromDisruptionId 是一种自定义方法,它在 API 上发出请求(使用“请求”NodeJS 模块)。

当然,我需要getDisruptionFromDisruptionId 提供的信息才能运行我的下一个循环...

此代码部分的父函数正在返回一个需要在两个循环结束时“填充”的回调。

有什么想法吗?

【问题讨论】:

  • request 是异步的,函数,你需要在你的代码中添加异步/等待或者使用递归
  • 现在添加 async/await 就像一个魅力!谢谢!

标签: javascript node.js loops for-loop request


【解决方案1】:

request 是异步函数,你需要在你的代码中添加 async / await 或者使用递归

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    相关资源
    最近更新 更多