Promise with recursion

前端 未结 4 1447
鱼传尺愫
鱼传尺愫 2021-01-06 06:35

I\'ve taken a look at a few questions on recursion in promises and am confused on how to implement them properly:

  • Recursive Promise in javascript
  • Angu
4条回答
  •  旧巷少年郎
    2021-01-06 07:10

    Many members already mentioned, need to resolve with the promise returned by the recursion.

    I would like to share code into async/await syntax.

    const printNumber = (i) => console.log("i is now: " + i);
    
    // recursive function to call number increment order
    const recursiveCallNumber = async (i, checkCondition) => {
        // if false return it, other wise continue to next step
        if (!checkCondition(i)) return;
        // then print
        printNumber(i); 
         // then call again for print next number
        recursiveCallNumber(++i, checkCondition);
    }
    
    await recursiveCallNumber(1, (i) => i <= 10);
    

提交回复
热议问题