在承诺链中调用两种方法

Call for two method in promise chain

本文关键字:两种 方法 调用 承诺      更新时间:2023-09-26

我有以下承诺,效果很好

troces.run(value, "../logs/env.txt")
    .then(function (data) {
        console.log(data);
        return updadeUser(val, arg, args[1])
        // Now here I need to add new method updateAddress(host,port,addr)
    }).catch(function (err) {
        console.error(err);
    });

现在我需要在第一个.then中添加其他方法调用更新用户和updateAddress将一起工作

我的问题是

  1. 假设更新用户需要在更新后 10 毫秒启动 地址 建议如何这样做?

  2. 在错误处理方面,如果其中一个进程失败(发送错误消息)我需要退出(process.exit(1);

使用 .all

troces.run(value, "../logs/env.txt")
.then(data => {
    console.log(data);
    return Promise.all([updadeUser(val, arg, args[1]),
                        updateAddress(host,port,addr)]);
}); // no need to add catches bluebird will log errors automatically

如果你真的需要10ms的延迟,你可以做到:

troces.run(value, "../logs/env.txt")
.then(data => {
    console.log(data);
    return Promise.all([updadeUser(val, arg, args[1]),
                        Promise.delay(10).then(x => updateAddress(host,port,addr))]);
}); // no need to add catches bluebird will log errors automatically

虽然我怀疑你真的只是想updateUser发生之前updateAddress可以很容易地解决:

troces.run(value, "../logs/env.txt")
.then(data => {
    console.log(data);
    return updadeUser(val, arg, args[1]).then(_ => updateAddress(host,port,addr));
}); // no need to add catches bluebird will log errors automatically

如果您需要在承诺错误时退出,您可以执行以下操作:

process.on("unhandledRejection", () => process.exit(1)); 

尽管我强烈建议您创建有意义的错误消息,但仅非零进程退出代码很难调试。