【问题标题】:Util function to chain multiple promise functions along with non promise functions at the endUtil 函数将多个 Promise 函数与最后的非 Promise 函数链接起来
【发布时间】:2019-09-18 15:36:18
【问题描述】:

对于纯 Promise 函数,我有一个方便的解决方案。但我需要一种方法来链接一组承诺函数,最后一个“then”将调用其他三个非承诺函数。

以下是我尝试过的

function chainMyPromises(promiseFunction, promiseArray){
    if(!promiseArray.length){
       return;
    }

  promiseFunction.then(()=>{
    const currentFunc = promiseArray.shift()
    return chainMyPromises(currentFunc(), promiseArray);
   });
}

const promiseArray = [functionOne, functionTwo, functionThree, functionFour];

function firstPromise(){
  return Promise.resolve(true);
}

chainMypromises(firstpromise, promiseArray);

下面是我的函数,它有一些基于 promise 的函数,最后一个“then”检查响应并调用三个非基于 promise 的函数。

function consolidatedReport(param1, param2){

   const somedata = param1.data;
   const someOtherData = param2.data;

  if(true){ 
     doThisthing(); 
   }

  return promiseChainBegin(somedata, someOtherData)
    .then(response => response && functionOne(somedata, someOtherData)
    .then(response => response && functionTwo(somedata, someOtherData)
    .then(response => response && functionThree(somedata, someOtherData)
    .then(response => response && functionFour(somedata, someOtherData)
    .then(response => {
       if(response) {
           notApromiseFuncOne(somedata)(someOtherData);
           notApromiseFuncTwo(somedata)(someOtherData);
           notApromiseFuncThree(somedata)(someOtherData);
        } else{
           notApromiseFailCase(someOtherData);
        }
    });
}

最后一个'then'调用三个不基于promise的函数。我需要一种方法来链接这些并整理它们。请提出重构它们的最佳方法。

【问题讨论】:

  • 所以notApromiseFuncOne等不是异步的吗?那么就没有问题了
  • @JaromandaX 怎么样?你能给我一个例子吗?如果我的 Util 函数都是异步函数,那么它可以正常工作,但因为最后我有非异步函数。在那里面对一个无赖。

标签: javascript reactjs ecmascript-6 promise


【解决方案1】:

为什么不使用像 Promise.all() 这样的东西:

    var promise1 = Promise.resolve(3);
    var promise2 = 42;
    var promise3 = new Promise(function(resolve, reject) {
      setTimeout(resolve, 100, 'foo');
    });

    Promise.all([promise1, promise2, promise3]).then(function(values) {
      console.log(values);
    }).catch(function(err){
      //If there is an execption it would be handled here
    });
    // expected output: Array [3, 42, "foo"]

这是处理多个 Promise 的一种更清晰的方式,然后您可以在最后一个 .then() 中执行所有基于非 Promise 的函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2020-02-18
    • 2017-02-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    相关资源
    最近更新 更多