Node.js For-Loop回调多个请求

时间:2017-09-13 06:25:38

标签: node.js for-loop asynchronous callback

我编写的代码与Bookeo的API一起使用,可以为不同的游览发布预订。但是,在POST之前,我需要检索eventId(由每个游览生成),作为检查该预订的可用插槽的方法。因此,对于我想要POST的每个预订,我需要事先获取并在我的POST中使用该变量。在研究之后我发现我需要进行回调,并且每个人都在推荐async / await / promise但它无论如何都无法通过我的头脑。我甚至不知道我是如何找出回调的。

我的代码遇到了超过5次预订的问题,我认为这与我的for循环有关,我循环电子表格的行,预先输入数据以进行预订(可能会干扰回调函数还是闭包?)

我试图找出如何将我的代码更改为可以使用async模块的代码。我试过了,但是我的代码还有很多,我甚至不确定什么是最适合我的异步解决方案。任何帮助将不胜感激,非常感谢你的时间。

function sheetToBookeo(auth) {
    var sheets = google.sheets('v4');
    sheets.spreadsheets.values.get({
        auth: auth,
        spreadsheetId: 'SPREADSHEETID',
        range: 'Bookeo Data!A3:K',
    }, function (err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            return;
        }
        var rows = response.values;
        if (rows.length === 0) {
            console.log('No data found.');
        } else {
            for (let i = 0; i < rows.length; i++) { //problem starts here.
                (function (i) {
                    var row = rows[i];
                    //User-defined
                    //Need to for loop all these variables with callback func
                    var productId = row[1];
                    var startTime = row[2]; //31day range, ISO format
                    var endTime = row[3];
                    var fName = row[4];
                    var nAdult = row[5];
                    var nChild = row[6];
                    var phoneNum = row[7];
                    var bookNumEmail = row[8];
                    var reseller = row[9]; //hardcoded to GYG
                    //Callback function due to request being asynchronous.
                    function getAvail(callback) {
                        Request.get('https://api.bookeo.com/v2/availability/slots?productId=' + productId + '&startTime=' + startTime + '&endTime=' + endTime + '&secretKey=' + secretKey + '&type=fixed&apiKey=' + apiKey,
                            function (error, response, body) {
                                if (!error && response.statusCode == 200) {
                                    const data = JSON.parse(body);
                                    var result = data["data"][0]["eventId"];
                                    console.log('Working callback!');
                                    return callback(false, result);
                                } else {
                                    return callback(error, null);
                                }
                            }
                        );
                    }

                    //GET available slots & POST after recieving body from GET
                    getAvail(function (err, data) {
                        if (!err) {
                            Request.post({
                                url: 'https://api.bookeo.com/v2/bookings?startTime=' + startTime + '&endTime=' + endTime + '&secretKey=' + secretKey + '&type=fixed&apiKey=' + apiKey,
                                json: {
                                    "eventId": data,
                                    "customer": {
                                        "firstName": fName,
                                        "lastName": bookNumEmail,
                                        "phoneNumbers": [
                                            {
                                                "number": phoneNum,
                                                "type": "mobile"
                                            }
                                        ],
                                        "customFields": [
                                            {
                                                "name": "Reseller",
                                                "value": "GetYourGuide" //Only works when hardcoded, cannot read spreadsheet reseller
                                            }
                                        ]
                                    },
                                    "participants": {
                                        "numbers": [
                                            {
                                                "peopleCategoryId": "Cadults",
                                                "number": nAdult
                                            },
                                            {
                                                "peopleCategoryId": "Cchildren",
                                                "number": nChild
                                            }
                                        ]
                                    },
                                    "productId": productId
                                },
                            },
                                function (error, response, body) {
                                    if (error) {
                                        throw error;
                                    }
                                    console.log('Working!');
                                });
                        }
                    }); //end func
                })(i);
            }
        }
    });
}

0 个答案:

没有答案