在两个函数完成之前发送消息

时间:2016-04-19 16:57:26

标签: javascript node.js data-synchronization

我正在使用pubchem-access模块​​为Node.JS bot检索化合物的某些化学属性,然后将它们发送到Telegram。我想组合几个属性并获得CAS标识符,但检索CAS标识符是一个单独的函数(请参阅:http://mmmalik.github.io/pubchem-access/#request)。 我试图将两者结合成一条消息,只需将所需的函数放在一起:

            case 'prop':
            var cas = ""
            pubchem
                .setName(commandText)
                .getCas()
                .execute(function(data, status) {
                    if (status != 1) {
                        cas = status;
                    } else {
                        cas = data
                    }
                });


            pubchem

                .setName(commandText)
                .getProperties(["IUPACName", "MolecularWeight", "MolecularFormula",
                    "CanonicalSMILES"
                ])
                .execute(function(data) {
                    msg.answer(
                        "IUPAC name: " + data.IUPACName + ",\nCAS :" + cas +
                        ",\nMW: " + data.MolecularWeight.toFixed(2) + ",\nFormula: " + data.MolecularFormula +
                        ", \nSMILES: " + data.CanonicalSMILES);
                });

            break;

我这样做的原因是,有时CAS资产尚未找到,而其他人则有,所以有时候邮件会在没有CAS的情况下发送。

如果只检索了所有想要的属性后,我该怎么做才能保证只发送消息?

抱歉,我的代码布局有问题

1 个答案:

答案 0 :(得分:1)

您可以将第二个请求包装在函数中,并在调用execute的回调函数时调用它

pubchem
.setName(commandText)
.getCas()
.execute(function(data, status) {
    var cas = !Object.is(status,1) ? status : data;
    doSecondRequest(cas);
});

function doSecondRequest(cas){
    pubchem
    .setName(commandText)
    .getProperties(["IUPACName", "MolecularWeight", "MolecularFormula","CanonicalSMILES"])
    .execute(function(data) {
        msg.answer(
            "IUPAC name: " + data.IUPACName + ",\nCAS :" + cas +
            ",\nMW: " + data.MolecularWeight.toFixed(2) + ",\nFormula: " + data.MolecularFormula +
            ", \nSMILES: " + data.CanonicalSMILES);
        });
}

或使用promises来处理异步调用

var promise = new Promise((resolve) => {
    pubchem
    .setName(commandText)
    .getCas()
    .execute((data, status) => {
        var cas = !Object.is(status,1) ? status : data;
        resolve(cas);
    });
};

promise.then((cas) => {
    pubchem
    .setName(commandText)
    .getProperties(["IUPACName", "MolecularWeight", "MolecularFormula","CanonicalSMILES"])
    .execute((data) => {
        msg.answer(
            "IUPAC name: " + data.IUPACName + ",\nCAS :" + cas +
            ",\nMW: " + data.MolecularWeight.toFixed(2) + ",\nFormula: " + data.MolecularFormula +
            ", \nSMILES: " + data.CanonicalSMILES);
     });
});