带有承诺的Node JS cron脚本

时间:2018-11-09 09:16:14

标签: javascript node.js asynchronous promise node-cron

我对JavaScript承诺很陌生。我正在尝试编写一个脚本来计算客户端的每台计算机的效率,而我需要处理的情况是班次中是否发生了模具更换,如果有那么多的话。现在,每个模具具有不同的目标生产,因此在给定的时间段内,效率随着生产的变化而变化。而且,这是我到目前为止提出的:

var request = require("request");
var cron = require("node-cron");
var express = require("express");
var async = require('async');
var userDetails;

app = express();

var clientId = 'clientId';
var idealCycletime = (6/60) ;
var downFor = (1000 * 60 * 5);
var assignedBreaks = (1000 * 60 * 45);
var apiUrl = 'http://apiUrl/';
var token = 'tokenValue';
var getMachines                         = apiUrl + 'getMachines/',
    getDie                              = apiUrl + 'getDie/',
    getDieLogs                          = apiUrl + 'getDieLogs/',
    getShiftTiming                      = apiUrl + 'getShiftTiming/',
    getCycleTimeLimited                 = apiUrl + 'getCycleTimeLimited/',
    countCycleTimeLimited               = apiUrl + 'countCycleTimeLimited/',
    getDowntimeLogs                     = apiUrl + 'getDowntimeLogs/',
    getComputedProduction               = apiUrl + 'getComputedProduction/';


cron.schedule("*/1 * * * *", function () {
    var machines = apiCall(getMachines, {'clientId': clientId}, 'POST'); //array of machines for the client eg: [{"machineId":"machineId", "hourlyTarget":"hourlyTarget", ...}, ....]
    var shiftTimings = apiCall(getShiftTiming, {'clientId': clientId}, 'POST'); //shiftTiming for the client eg: {"clientId":"clientId", shiftA":"08:00:00", "shiftB":"20:00:00", "shiftC":""}
    var shiftTiming;
    var currentDateTime = IST();
    console.log(currentDateTime);
    var endDateTime = new Date(currentDateTime);
    endDateTime.setSeconds(00);
    endDateTime.setMilliseconds(000);
    var startDateTime = new Date(endDateTime);
    startDateTime.setMinutes(startDateTime.getMinutes() - 6);
    var hours = endDateTime.getHours() < 10 ? "0" + endDateTime.getHours() : endDateTime.getHours();
    var minutes = endDateTime.getMinutes() < 10 ? "0" + endDateTime.getMinutes() : endDateTime.getMinutes();
    var seconds = endDateTime.getSeconds() < 10 ? "0" + endDateTime.getSeconds() : endDateTime.getSeconds();
    var currentTime = hours + ":" + minutes + ":" + seconds;
    var shiftAStartDateTime = new Date(endDateTime); 
    var shiftBStartDateTime = new Date(endDateTime); 
    var shiftCStartDateTime = new Date(endDateTime);
    var prodDate;

    shiftTimings.then(JSON.parse)
        .then(function(shifts) {
            if (shifts.shiftC == '') {
                shiftAStartDateTime.setHours(shifts.shiftA[0]+shifts.shiftA[1]);
                shiftAStartDateTime.setMinutes(shifts.shiftA[3]+shifts.shiftA[4]);

                shiftBStartDateTime.setHours(shifts.shiftB[0]+shifts.shiftB[1]);
                shiftBStartDateTime.setMinutes(shifts.shiftB[3]+shifts.shiftB[4]);
            } else {
                shiftAStartDateTime.setHours(shifts.shiftA[0]+shifts.shiftA[1]);
                shiftAStartDateTime.setMinutes(shifts.shiftA[3]+shifts.shiftA[4]);

                shiftBStartDateTime.setHours(shifts.shiftB[0]+shifts.shiftB[1]);
                shiftBStartDateTime.setMinutes(shifts.shiftB[3]+shifts.shiftB[4]);

                shiftCStartDateTime.setHours(shifts.shiftC[0]+shifts.shiftC[1]);
                shiftCStartDateTime.setMinutes(shifts.shiftC[3]+shifts.shiftC[4]);
            }
            if (currentTime >= "00:00:00" && currentTime < shifts.shiftA) {
                shiftAStartDateTime.setDate(shiftAStartDateTime.getDate()-1);
                shiftBStartDateTime.setDate(shiftBStartDateTime.getDate()-1);
                shiftCStartDateTime.setDate(shiftCStartDateTime.getDate()-1);
                var month = ('0' + (shiftAStartDateTime.getMonth() + 1)).slice(-2);
                var day = ('0' + shiftAStartDateTime.getDate()).slice(-2);
                var year = shiftAStartDateTime.getFullYear();
                prodDate = year + "-" + month + "-" + day;
            }
            else{
                var month = ('0' + (shiftAStartDateTime.getMonth() + 1)).slice(-2);
                var day = ('0' + shiftAStartDateTime.getDate()).slice(-2);
                var year = shiftAStartDateTime.getFullYear();
                prodDate = year + "-" + month + "-" + day;
            }
            shiftTiming = shifts;
            var machines = apiCall(getMachines, {'clientId': clientId}, 'POST').then(JSON.parse);
            return machines;
        }).then(function(allMachines) {
            async.map(allMachines , function(machine, callback) {
                // console.log(machine.machineId);
                var machineDataA, machineDataB, machineDataC, machineDataNow; 
                var currentShiftALength = 0, currentShiftBLength = 0, currentShiftCLength = 0;
                var downtimeA = 0, uptimeA = 0, downtimeB = 0, uptimeB = 0, downtimeC = 0, uptimeC = 0;
                var utilizationShiftA = 0, utilizationShiftB = 0, utilizationShiftC = 0;
                var utilizationShiftAData = 0, utilizationShiftBData = 0, utilizationShiftCData = 0;
                var efficiencyShiftA = 0, efficiencyShiftB = 0, efficiencyShiftC = 0;
                var efficiencyShiftAData = 0, efficiencyShiftBData = 0, efficiencyShiftCData = 0;
                var goodCountA = 0, totalCountA = 0, rejectCountA = 0, targetCountA = 0;
                var goodCountB = 0, totalCountB = 0, rejectCountB = 0, targetCountB = 0;
                var goodCountC = 0, totalCountC = 0, rejectCountC = 0, targetCountC = 0;
                var goodCountNow = 0, totalCountNow = 0, rejectCountNow = 0, targetCountNow = 0;
                var qualityShiftA = 0, qualityShiftB = 0, qualityShiftC = 0;
                var performanceShiftA = 0, performanceShiftB = 0, performanceShiftC = 0;
                var oeeShiftA = 0, oeeShiftB = 0, oeeShiftC = 0;
                var oeeShiftAData = 0, oeeShiftBData = 0, oeeShiftCData = 0;
                // console.log(currentDateTime);
                if (shiftTiming.shiftC == '') {
                    if (true) {
                        machineDataA = {
                            'machineId' : machine.machineId,
                            'startDateTime' : shiftAStartDateTime,
                            'endDateTime' : shiftBStartDateTime,
                            'eDate' : prodDate
                        };
                        machineDataB = {
                            'machineId' : machine.machineId,
                            'startDateTime' : shiftBStartDateTime,
                            'endDateTime' : endDateTime,
                            'eDate' : prodDate
                        };
                        // console.log(machineDataA);
                        currentShiftALength = (endDateTime - shiftAStartDateTime)/(1000 * 60);
                        var dieLogsA = apiCall(getDieLogs, machineDataA, 'POST');

                        dieLogsA.then(JSON.parse)
                            .then(function(dieLogs) { 
                            //dieLogs Array eg: 
                            // [{    
                            //     "id" : "5500A24141F7",
                            //     "machineId" : "DEMOAISPL1",
                            //     "dateTime" : ISODate("2018-09-11T04:59:29.000Z"),
                            //     "startDateTime" : ISODate("2018-09-11T04:59:29.000Z"),
                            //     "endDateTime" : ISODate("2018-09-11T04:59:38.000Z"),
                            //     "clientId" : "DEMO"
                            // },
                            // {
                            //     "id" : "5500A24141F7",
                            //     "machineId" : "DEMOAISPL1",
                            //     "dateTime" : ISODate("2018-09-11T04:59:57.000Z"),
                            //     "startDateTime" : ISODate("2018-09-11T04:59:57.000Z"),
                            //     "endDateTime" : ISODate("2018-09-11T05:00:06.000Z"),
                            //     "clientId" : "DEMO"
                            // }]
                                if (dieLogs == '') {
                                    var actualA = apiCall(countCycleTimeLimited, machineDataA, 'POST').then(JSON.parse).then(function(countA) {
                                        totalCountA = countA['count'];
                                        if (machine.currentDie != '') {
                                            var targetA = apiCall(getDie, {'dieId' : machine.currentDie}, 'POST').then(JSON.parse).then(function(dieA) {
                                                targetCountA = (dieA['target']/60)*currentShiftALength;
                                                efficiencyShiftA = efficiency(totalCountA,targetCountA)*100;
                                                // console.log(machine.machineId,totalCountA,targetCountA, efficiencyShiftA);
                                            });
                                        } else {
                                            targetCountA = (machine.hourlyTarget/60)*currentShiftALength;
                                            efficiencyShiftA = efficiency(totalCountA,targetCountA)*100;
                                            // console.log(machine.machineId,totalCountA,targetCountA, efficiencyShiftA);
                                        }
                                    });
                                } else {
                                    var eff = [];
                                    var betweenDies =[];
                                    var i;
                                    for (i = 0; i <= dieLogs.length; i++) {
                                        var dieStart, dieEnd, timeDiff;
                                        if (i == 0) {
                                            dieStart = new Date(dieLogs[i]['startDateTime']);
                                            dieEnd = new Date(dieLogs[i]['endDateTime']);
                                            if (dieStart < shiftAStartDateTime) {
                                                dieStart = new Date(shiftAStartDateTime);
                                                dieEnd = new Date(dieLogs[i]['endDateTime']);
                                                timeDiff = (dieEnd - dieStart)/(1000 * 60);
                                                var targetA = apiCall(getDie, {'dieId' : dieLogs[i]['id']}, 'POST').then(JSON.parse).then(function(dieA) {
                                                    targetCountA = (dieA['target']/60)*timeDiff;
                                                    machineDataA = {
                                                        'machineId' : machine.machineId,
                                                        'startDateTime' : dieStart,
                                                        'endDateTime' : dieEnd,
                                                        'eDate' : prodDate
                                                    };
                                                    var actualA = apiCall(countCycleTimeLimited, machineDataA, 'POST').then(JSON.parse).then(function(countA) {
                                                        totalCountA = countA['count'];
                                                        efficiencyShiftA = efficiency(totalCountA,targetCountA)*100;
                                                        eff.push(efficiencyShiftA);
                                                    });
                                                });
                                            } else {
                                                dieStart = new Date(dieLogs[i]['startDateTime']);
                                                dieEnd = new Date(dieLogs[i]['endDateTime']);
                                                timeDiff = (dieEnd - dieStart)/(1000 * 60);
                                                var targetA = apiCall(getDie, {'dieId' : dieLogs[i]['id']}, 'POST').then(JSON.parse).then(function(dieA) {
                                                    targetCountA = (dieA['target']/60)*timeDiff;
                                                    machineDataA = {
                                                        'machineId' : machine.machineId,
                                                        'startDateTime' : dieStart,
                                                        'endDateTime' : dieEnd,
                                                        'eDate' : prodDate
                                                    };
                                                    var actualA = apiCall(countCycleTimeLimited, machineDataA, 'POST').then(JSON.parse).then(function(countA) {
                                                        totalCountA = countA['count'];
                                                        efficiencyShiftA = efficiency(totalCountA,targetCountA)*100;
                                                        console.log('0', efficiencyShiftA);
                                                        eff.push(efficiencyShiftA);
                                                    });
                                                });
                                            }
                                        } else if (i == dieLogs.length) {
                                            dieStart = new Date(dieLogs[i-1]['startDateTime']);
                                            dieEnd = new Date(endDateTime);
                                            timeDiff = (dieEnd - dieStart)/(1000 * 60);
                                            machineDataA = {
                                                'machineId' : machine.machineId,
                                                'startDateTime' : dieStart,
                                                'endDateTime' : dieEnd,
                                                'eDate' : prodDate
                                            };
                                            var actualA = apiCall(countCycleTimeLimited, machineDataA, 'POST').then(JSON.parse).then(function(countA) {
                                                totalCountA = countA['count'];
                                                if (machine.currentDie != '') {
                                                    var targetA = apiCall(getDie, {'dieId' : machine.currentDie}, 'POST').then(JSON.parse).then(function(dieA) {
                                                        targetCountA = (dieA['target']/60)*timeDiff;
                                                        efficiencyShiftA = efficiency(totalCountA,targetCountA)*100;
                                                        eff.push(efficiencyShiftA);
                                                    });
                                                } else {
                                                    targetCountA = (machine.hourlyTarget/60)*timeDiff;
                                                    efficiencyShiftA = efficiency(totalCountA,targetCountA)*100;
                                                    eff.push(efficiencyShiftA);
                                                }
                                            }).then(function () {
                                                var effShiftA = 0;
                                                for (var i = 0; i < eff.length; i++) {
                                                    effShiftA = effShiftA + eff[i];
                                                }
                                                efficiencyShiftA = effShiftA/eff.length;    
                                            }).then(function () {
                                                console.log(eff);
                                                console.log(machine.machineId,totalCountA,targetCountA, efficiencyShiftA);      
                                            });
                                        } else {
                                            dieStart = new Date(dieLogs[i]['startDateTime']);
                                            dieEnd = new Date(dieLogs[i]['endDateTime']);
                                            timeDiff = (dieEnd - dieStart)/(1000 * 60);
                                            var targetA = apiCall(getDie, {'dieId' : dieLogs[i]['id']}, 'POST').then(JSON.parse).then(function(dieA) {
                                                targetCountA = (dieA['target']/60)*timeDiff;
                                                machineDataA = {
                                                    'machineId' : machine.machineId,
                                                    'startDateTime' : dieStart,
                                                    'endDateTime' : dieEnd,
                                                    'eDate' : prodDate
                                                };
                                                var actualA = apiCall(countCycleTimeLimited, machineDataA, 'POST').then(JSON.parse).then(function(countA) {
                                                        totalCountA = countA['count'];
                                                    efficiencyShiftA = efficiency(totalCountA,targetCountA)*100;
                                                    console.log('2', efficiencyShiftA);
                                                    eff.push(efficiencyShiftA);
                                                });
                                            });
                                        }
                                        console.log(i);
                                    }
                                }
                            }).catch(function (err) {
                                console.log('I caught your error! inside the loop' );
                            });
                    } else {
                        console.log('shift b else');
                    }
                } else {
                    console.log('shift c else');
                }
            });
        }).catch(function (err) {
            console.log('I caught your error!' );
        });

    // machines.then(JSON.parse, errHandler)
    //              .then(function(allMachines) {
    //                 async.map(allMachines , function(machine, callback) {
                //      // console.log(machine.machineId);
                //     });
    //                 // console.log(result);
    //                 // Do one more async operation here
    //                 // var anotherPromise = getData(userDetails.followers_url, null, 'GET').then(JSON.parse);
    //                 // return anotherPromise;
    //             }, errHandler);
    //             // .then(function(data) {
    //             //     console.log(data)
    //             // }, errHandler);
});

function apiCall(url, requestData, method) {
    // Setting URL and headers for request
    var options = {
        url: url,
        form: requestData,
        headers: {
            "Authorization":"JWT " + token,
            'User-Agent': 'request'
        },
        method: method
    };
    // Return new promise 
    return new Promise(function(resolve, reject) {
        // Do async job
        request(options, function(err, resp, body) {
            if (err) {
                reject(err);
            } else {
                resolve(body);
            }
        })
    })
}

var errHandler = function(err) {
    console.log(err);
}

function IST(){
  var dateUTC = new Date();
  var dateUTC = dateUTC.getTime(); 
  var dateIST = new Date(dateUTC);
  //converting date time to IST
  dateIST.setHours(dateIST.getHours() + 5); 
  dateIST.setMinutes(dateIST.getMinutes() + 30);
  return dateIST;
}

function efficiency(actual,target)
{
    return (actual/target);
}

app.listen(3129);

假设for循环应运行4次并向eff数组添加4个元素,有时它只运行一次并向数组添加1个元素,有时它运行3次,并且仅添加2个元素,因此从不运行4次我希望阵列中的所有效率都不会发生,即使是控制台也是如此。有时日志是错误的,因为未返回预期的结果,所以我不知道我要去哪里哪里

0 个答案:

没有答案