在节点中,使用Q,使两个函数并行工作,但只等待第一个函数实现其承诺

in node, using Q, make 2 functions work in parallel but wait only for the first one to fulfill its promise

本文关键字:函数 工作 并行 第一个 承诺 实现 等待 使用 节点 两个      更新时间:2023-09-26

在我的环境中,我使用node+q(我不是这方面的专家),所以主要参数是:promise。

我有一个函数,需要并行进行两个操作,一个很长的操作和一个很短的操作。

var parallelWrapper = function(input) {
  var deferred = Q.defer();
  var fastPromise = fastComputation()
    .then(function(data) {
        deferred.resolve(data)
      },
      function(err) {
        deferred.reject(err)
      });
  // of course this one below is not going to work properly
  var slowPromise = slowComputation()
    .then(function(data) {
      makeSomething();
    })
    .then(function(data) {
      makeSomethingElse();
    })
    .fail(function(err) {
      console.log(err);
    });
  Q.all([fastPromise, slowPromise]);
  retrun deferred.promise;
}

此函数将在promise链中调用,因为需要第一个操作的结果,而不需要第二个操作的效果。

var myLongChainOfFunctions = function() {
  var deferred = Q.defer();
  firstFunction(someParams)
    .then(secondFunction)
    .then(thirdFunction)
    /*...*/
    .then(parallelWrapper)
    .then(someFunction(data){
      /* Do Something with the data returned only by fastPromise*/
    }
    /*...*/
    .then(lastFunction)
    .fail(doSomething)
  return deferred.promise;
}

我想做的是让它们并行,但在fastPromise完成后尽快解决,这样连锁的承诺就可以向前推进,但很明显,在未来的某个时候,我也希望slowPromise完成。所以我只希望slowPromise过它的生活,做它必须做的事,不要太在乎成功或失败。

我的印象是Q是不可能的,但也许有一个我没有发现的解决方案。

我会这么做的:

var parallelWrapper = function(input) {
  var fastPromise = fastComputation();
  var slowPromise = slowComputation()
    .then(function(data) {
      return makeSomething();
    })
    .then(function(data) {
      return makeSomethingElse();
    }).catch(console.error);
  return Q([fastPromise, slowPromise]).all();
}

第二个例子是这样的:

var myLongChainOfFunctions = function() {
  return firstFunction(someParams)
    .then(secondFunction)
    .then(thirdFunction)
    /*...*/
    .then(parallelWrapper)
    /*...*/
    .then(lastFunction)
    .catch(doSomethingWithError)
}

好的,你可以这样做:

var parallelWrapper = function(input) { 
      slowComputation()
        .then(function(data) {
          return makeSomething();
        })
        .then(function(data) {
          return makeSomethingElse();
        }).catch(console.error);
      return fastComputation();
    }