简体   繁体   English

将promise与递归函数一起使用

[英]Use promises with recursive function

I am trying to figure out if it's possible to use promises instead of a standard callback in a recursive function. 我试图找出是否有可能在递归函数中使用promise而不是标准回调。

The way I have it now: 我现在拥有的方式:

function recursive(data, cb){

     (function promiseProvider(data){

          return newThenable(data).then(function(val){
                 if(val.a){
                    cb(null, val);
                 }
                 else {
                    return promiseProvider(val);
                 }

          });

     })(data);

}

This works, but I can't figure out how I could make a pure promise implementation. 这行得通,但是我无法弄清楚如何实现纯粹的promise实现。

Perhaps this would work? 也许这行得通吗?

  function recursive(data){

      return newThenable(data).then(function(val){
               if(val.a){
                  return // <<< ???
                 }
                 else {
                   return recursive(val);
                 }

        });

     }

However, that doesn't work. 但是,这不起作用。

Given you were calling the callback with val as the result argument, just 假设您使用val作为结果参数调用回调,则只需

return val;

from the then callback. then回调。 That's it. 而已。

function recursive(data){
     return newThenable(data).then(function(val){
         if (val.a){
             return val;
         } else {
             return recursive(val);
         }
     });
 }

Push val to an array. val推到数组。 If val.a return array of results, else call recursive with val and array of accumulates results as parameter. 如果val.a返回结果数组,否则使用val调用recursive ,并将累加结果数组作为参数。 See multiple, sequential fetch() Promise 查看多个顺序的fetch()承诺

  function recursive(data, results) {
    return newThenable(data).then(function(val) {
      if (val.a) {
        // results.push(val);
        return results
      } else {
        results.push(val);
        return recursive(val, results).catch(function(e) {console.log(e)});
      }
    });
  }

Nowadays the ES8 async/await makes it more readable. 如今,ES8异步/等待使其更具可读性。 I skipped the try-catch for now. 我暂时跳过了try-catch。

async function recursive(data, results = []) {
    let val = await newThenable(data);
    if (val.a) {
        return results
    } else {
        results.push(val);
        return recursive(val, results);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM