【问题标题】:Promise then is called before the before the previous then was finishedPromise then 在前一个 then 完成之前被调用
【发布时间】:2016-05-13 07:45:59
【问题描述】:

我有以下代码的节点应用程序:

当我运行节点应用程序时,console.log("after start") 被称为 before 开始已经完成,我需要 开始 完成之后, 我在这里做错了什么?

myprocess.start(function() {
  //this is called before the start was finished.
  console.log("After start");
  server.listen(app.get('port'), function(err) {
    if (err) {
      console.error(err);
    } else {
      console.log(' listen to: ' + app.get('port'));
    }

  });
});

文件 myprocess.js 包含以下内容

exports.start = function (callback) {

    Validator.validateJson(function (err) {
        console.log(err);
        process.exit(1);
    });

    plugin.parse().then(function (configObj) {
        if (typeof require.cache.persist === 'undefined') {
            require.cache.persist = {};
        }
        require.cache.persist.configObj = configObj;
    }, function (err) {
        console.log(err);
    });

    var run= function () {
        return Promise.all([
            childPro.create(path.join(value)),
            childPro.findAndUpdateUser()
        ]).spread(function (cmd,updatppEnv) {
            return Promise.all([childProc.executeChildProcess('exec', cmd, updatedAppEnv), Promise.delay(50).then(function (results) {
                return inter.ProcessRun(val);
            })]);
        })
    }();

 //I want that this callback will be called after the run promise will be finished 
 run.then(callback());

}

如何在所有启动过程完成后让服务器代码运行

更新

对我来说,等到inter.ProcessRun(val) 就足够了;解决了调用回调怎么办?

【问题讨论】:

  • childProc.executeChildProcess() 是否返回承诺? Promise.all() 只能等待异步操作,如果你给它一个承诺。它没有任何神奇的力量可以知道何时完成了一些异步操作。异步操作必须返回一个承诺并在完成后履行该承诺。正如其他人所说,run.then(callback()); 也应该是run.then(callback);,所以.then() 可以在准备好后调用回调,而不是立即调用。
  • @jfriend00 - 谢谢!我不知道 executeChildProcess 的承诺何时解决,但我想在运行完成后执行回调...
  • @jfriend00 - 只是为了验证 inter.ProcessRun 已解决以继续运行到回调就足够了,那么我应该改变什么......
  • 当您使用所有这些函数时,我们无法真正为您提供很好的帮助,而且我们不知道哪些返回承诺,哪些不返回。 inter.ProcessRun() 是否返回承诺? childProc.executeChildProcess() 是否返回承诺?
  • @jfriend00 - processRun 已解决,但 childProcess 有时没有...

标签: javascript node.js callback promise bluebird


【解决方案1】:

您通过执行run.then(callback()) 立即调用callback。你想要run.then(callback)

【讨论】:

  • 谢谢,但是当我删除 () 后,我在启动后看不到消息,即服务器代码未被调用...
  • 第一个console.log没有调用console.log("After start");和服务器代码...
  • @shopiaT:那么,可能进入Promise.all 的承诺之一永远不会得到解决,或者因为错误而被拒绝?
【解决方案2】:

我猜你忘记了退货声明。 试试

return run.then(callback);

【讨论】:

  • 谢谢,我试了一下,但没有帮助,还有其他想法吗?
猜你喜欢
  • 2019-03-07
  • 2019-02-22
  • 1970-01-01
  • 2019-01-10
  • 1970-01-01
  • 2018-04-05
  • 2019-08-01
  • 1970-01-01
  • 2020-12-27
相关资源
最近更新 更多