在promise链中调用两个方法

时间:2016-01-21 09:20:56

标签: javascript node.js promise bluebird

我的以下承诺效果很好

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. 假设updateUser需要在更新后10毫秒启动   地址如何建议这样做?

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

  4.   

1 个答案:

答案 0 :(得分: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

如果确实需要10毫秒延迟,您可以执行以下操作:

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

虽然我怀疑你真的希望{<1}}在 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

虽然我热烈建议您创建有意义的错误消息,但只是非零进程退出代码很难调试。