Javascript NodeJS将承诺转换为承诺

Javascript NodeJS将承诺转换为承诺,javascript,node.js,asynchronous,promise,Javascript,Node.js,Asynchronous,Promise,我有一个我一直在努力的NodeJS脚本,但我最大的问题是,将所有这些承诺链接起来不仅难看,而且随着时间的推移很难维护 我想使用Promise.all()方法将这些承诺转换为一个承诺,但不确定如何使用此方法获得相同的功能并将变量从一个承诺分配给另一个承诺 例如,我的第二个承诺:methods.login()返回几乎所有其他承诺中都使用的sessionId。如何使用Promise.all(),分配该变量并将其传递给其他相关承诺 这是我目前的代码: var zabbixApi = require('.

我有一个我一直在努力的NodeJS脚本,但我最大的问题是,将所有这些承诺链接起来不仅难看,而且随着时间的推移很难维护

我想使用
Promise.all()
方法将这些承诺转换为一个承诺,但不确定如何使用此方法获得相同的功能并将变量从一个承诺分配给另一个承诺

例如,我的第二个承诺:
methods.login()
返回几乎所有其他承诺中都使用的sessionId。如何使用
Promise.all()
,分配该变量并将其传递给其他相关承诺

这是我目前的代码:

var zabbixApi = require('./zabbixapi.js');
var methods   = require('./methods.js');
var fs        = require('fs');
var SESSIONID;

function main() {
    var apiVersion, loggedOut, numTemplates, numHosts, numHostGroups, numItems;
    var templates = []
        , hostGroups = []
        , hosts = [];

    /*var promises = [];
    promises.push(zabbixApi(methods.getApiVersion()));
    promises.push(zabbixApi(methods.login(SESSIONID)));
    promises.push(zabbixApi(methods.getHostGroups(SESSIONID)));
    promises.push(zabbixApi(methods.getTemplates(SESSIONID)));
    promises.push(zabbixApi(methods.getHosts(SESSIONID)));
   // promises.push(zabbixApi(methods.configExport(hostIds, templateIds, groupIds, SESSIONID)));
    promises.push(zabbixApi(methods.logout(SESSIONID)));

    Promise.all(promises).then(function (values) {
       console.log('All promises completed.');

    }, function (reason) {
        console.log('Error completing promises: ' + reason);
    });*/


    // Get API version
    zabbixApi(methods.getApiVersion())

    // If successful, login to the API
    .then(function (version) {
        apiVersion = version.result;

        // Verify that the API version returned is correct
        if (apiVersion.length < 5 || !apiVersion) {
            console.log('Error occurred retrieving API version: ' + version.error.data);
            return 1;
        } else {
            return zabbixApi(methods.login(SESSIONID));
        }

    }, function (error) {
        console.log('Error occurred retrieving API version: ' + error);
        return 1;

        // If login successful, continue operations until logged out or error
    }).then(function (auth) {
        SESSIONID = auth.result;

        if (!SESSIONID) {
            console.log('Error retrieving session id: ' + auth.error.data);
            return 1;
        } else {
            console.log('Logged in successfully!');
            return zabbixApi(methods.getHostGroups(SESSIONID));
        }

    }, function (error) {
        console.log('Error occurred authenticating: ' + error);
        return 1;

        // Attempt to retrieve all hostgroup information
    }).then(function (hostgroups) {
        numHostGroups = hostgroups.result.length;
        hostGroups = hostgroups.result;

        if (!numHostGroups) {
            console.log('Error occurred retrieving host groups: ' + hostgroups.error.data);
            return 1;
        } else {
            return zabbixApi(methods.getTemplates(SESSIONID));
        }


    }, function (error) {
        console.log('Error occurred retrieving host groups: ' + error);
        return 1;

        // Attempt to retrieve host information
    }).then(function (template) {
        numTemplates = template.result.length;
        templates = template.result;

        if (!numTemplates) {
            console.log('Error occurred retrieving templates: ' + template.error.data);
            return 1;
        } else {
            return zabbixApi(methods.getHosts(SESSIONID));
        }


    }, function (error) {
        console.log('Error occurred retrieving templates: ' + error);
        return 1;

        // Attempt to retrieve host information
    }).then(function (hosts) {
        numHosts = hosts.result.length;
        hosts    = hosts.result;

        if (!numHosts) {
            console.log('Error occurred retrieving host groups: ' + hosts.error.data);
            return 1;
        } else {
            var groupIds      = []
                , hostIds     = []
                , templateIds = [];

            // Extract all groupIds for host groups
            for (var i = 0; i < numHostGroups; i++) {
                groupIds[i] = hostGroups[i].groupid;
            }
            // Extract all hostIds for hosts
            for (var i = 0; i < numHosts; i++) {
                hostIds[i] = hosts[i].hostid;
            }
            // Extract all templateIds for templates
            for (var i = 0; i < numTemplates; i++) {
                templateIds[i] = templates[i].templateid;
            }
            return zabbixApi(methods.configExport(hostIds, templateIds, groupIds, SESSIONID));
        }

    }, function (error) {
        console.log('Error occurred retrieving host groups: ' + error);
        return 1;

        // Attempt to retrieve configuration information
    }).then(function (config) {
        //console.log(config);
        if (config.error) {
            console.log('Error occurred retrieving configuration: ' + config.error.message + ': ' + config.error.data);
            return 1;
        } else {
            if (!writeToFile(config)) {
                return 1;
            } else {
                console.log('Configuration details exported successfully.');

            }
            return zabbixApi(methods.logout(SESSIONID));
        }

    }, function (error) {
        console.log('Error occurred retrieving configuration: ' + error);
        return 1;

        // Attempt to logout of API, if logout successful exit safely
    }).then(function (logout) {
        loggedOut = logout.result;
        if (!loggedOut) {
            console.log('Error logging out: ' + logout.error.data);
            return 1;
        } else {
            console.log('Logged out successfully!');
            return 0;
        }

    }, function (error) {
        console.log('Error occurred logging out: ' + error);
        return 1;
    });
}

function writeToFile (config) {
    fs.writeFile('zabbix_config_export.json', JSON.stringify(config), function (err) {
        if (err) {
            return console.log('Error writing configuration to file: ' + err);
        }
    });
    return true;
}
main();
var-zabbixApi=require('./zabbixApi.js');
var-methods=require('./methods.js');
var fs=需要('fs');
无柄变异体;
函数main(){
变量apiVersion、loggedOut、numTemplates、numHosts、numHostGroups、numItems;
var模板=[]
,主机组=[]
,主机=[];
/*var承诺=[];
push(zabbixApi(methods.getApiVersion());
promises.push(zabbixApi(methods.login(SESSIONID));
push(zabbixApi(methods.getHostGroups(SESSIONID));
push(zabbixApi(methods.getTemplates(SESSIONID));
push(zabbixApi(methods.getHosts(SESSIONID));
//push(zabbixApi(methods.configExport(hostIds、templateid、groupid、SESSIONID));
promises.push(zabbixApi(methods.logout(SESSIONID));
承诺。所有(承诺)。然后(函数(值){
console.log(“完成所有承诺”);
},功能(原因){
console.log('完成承诺时出错:'+原因);
});*/
//获取API版本
zabbixApi(methods.getApiVersion())
//如果成功,请登录到API
.then(功能(版本){
apiVersion=version.result;
//验证返回的API版本是否正确
如果(apiVersion.length<5 | | |!apiVersion){
console.log('检索API版本时出错:'+version.Error.data);
返回1;
}否则{
返回zabbixApi(methods.login(SESSIONID));
}
},函数(错误){
console.log('检索API版本时出错:'+错误);
返回1;
//如果登录成功,请继续操作,直到注销或出现错误
}).then(函数(auth){
SESSIONID=auth.result;
if(!SESSIONID){
log('检索会话id时出错:'+auth.Error.data);
返回1;
}否则{
console.log('登录成功!');
返回zabbixApi(methods.getHostGroups(SESSIONID));
}
},函数(错误){
console.log('验证时出错:'+错误);
返回1;
//尝试检索所有主机组信息
}).then(功能(主机组){
numHostGroups=hostgroups.result.length;
hostGroups=hostGroups.result;
if(!numHostGroups){
console.log('检索主机组时出错:'+hostgroups.Error.data);
返回1;
}否则{
返回zabbixApi(methods.getTemplates(SESSIONID));
}
},函数(错误){
console.log('检索主机组时出错:'+错误);
返回1;
//尝试检索主机信息
}).then(功能(模板){
numTemplates=template.result.length;
templates=template.result;
如果(!numTemplates){
console.log('检索模板时出错:'+template.Error.data);
返回1;
}否则{
返回zabbixApi(methods.getHosts(SESSIONID));
}
},函数(错误){
console.log('检索模板时出错:'+错误);
返回1;
//尝试检索主机信息
}).then(功能(主机){
numHosts=hosts.result.length;
hosts=hosts.result;
如果(!numHosts){
console.log('检索主机组时出错:'+hosts.Error.data);
返回1;
}否则{
var groupIds=[]
,主机ID=[]
,templateId=[];
//提取主机组的所有GroupID
对于(var i=0;igetApiVersion  
Login to session  
In parallel (getHostGroups, getTemplates, getHosts)  
configExport previous results  
In parallel (logout, writeToFile) 
var zabbixApi = require('./zabbixapi.js');
var methods   = require('./methods.js');
var fs        = require('fs');
var SESSIONID;

function logout() {
    if (SESSIONID) {
        var p = zabbixApi(methods.logout(SESSIONID));
        // clear SESSIONID to show that we've already launched a logout attempt, no need to try again
        SESSIONID = null;
        return p;
    } else {
        return Promise.resolve();
    }
}

function main() {
    var apiVersion, hostGroups, templates, hosts;

    // Get API version
    zabbixApi(methods.getApiVersion())

    // If successful, login to the API
    .then(function (version) {
        apiVersion = version.result;

        // Verify that the API version returned is correct
        if (!apiVersion || apiVersion.length < 5) {
            throw new Error('Error occurred retrieving API version: ' + version.error.data);
        } else {
            return zabbixApi(methods.login(SESSIONID));
        }

    }, function (error) {
        throw new Error('Error occurred retrieving API version: ' + error);

    // If login successful, continue operations until logged out or error
    }).then(function (auth) {
        SESSIONID = auth.result;

        if (!SESSIONID) {
            throw new Error('Error retrieving session id: ' + auth.error.data);
        } else {
            console.log('Logged in successfully!');

            // now that we are logged in, a number of operations can be launched in parallel
            return Promise.all([
                zabbixApi(methods.getHostGroups(SESSIONID),
                zabbixApi(methods.getTemplates(SESSIONID),
                zabbixApi(methods.getHosts(SESSIONID)
            ]);
        }
    }, function (error) {
        throw new Error('Error occurred authenticating: ' + error);

    // we have hostGroups, templates and hosts here
    }).then(function(r) {
        // r[0] = hostGroups, r[1] = templates, r[2] = hosts

        // check hostGroups
        hostGroups = r[0].result;
        if (!hostGroups.length) {
            throw new Error('Error occurred retrieving host groups: ' + hostgroups.error.data);
        }

        // check templates
        templates = r[1].result;
        if (!templates.length) {
            throw new Error('Error occurred retrieving templates: ' + template.error.data);
        }

        // check host information
        hosts = r[2].result;
        if (!hosts.length) {
            throw new Error('Error occurred retrieving host groups: ' + hosts.error.data);
        }

        // utility function for retrieving a specific property from each array of objects
        function getIds(array, prop) {
            return array.map(function(item) {
                return item[prop];
            });
        }

        var groupIds = getIds(hostGroups, "groupid");
        var hostIds = getIds(hosts, "hostid");
        var templateIds = getIds(templates, "templateid");
        return zabbixApi(methods.configExport(hostIds, templateIds, groupIds, SESSIONID));
    }).then(function(config) {
        if (config.error) {
            throw new Error('Error occurred retrieving configuration: ' + config.error.message + ': ' + config.error.data);
        }
        // simultaneously write to file and logout (since these are not dependent upon one another)
        return Promise.all(logout(), writeToFile(config));
    }).then(function() {
        // success here, everything done
    }, function(err) {
        // upon error, try to logout and rethrow earlier error
        return logout().then(function() {
            throw err;
        }, function() {
            throw err;
        });
    }).then(null, function(err) {
        // error here
        console.log(err);
    });

}

function writeToFile (config) {
    return new Promise(function(resolve, reject) {
        fs.writeFile('zabbix_config_export.json', JSON.stringify(config), function (err) {
            if (err) {
                return Promise.reject(new Error('Error writing configuration to file: ' + err));
            }
            resolve();
        });
    });
}
main();