Promise with recursion

前端 未结 4 1456
鱼传尺愫
鱼传尺愫 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:31

    Try not to use shared mutable state in your functions (especially when they are asynchronous). You are using window.i but anything can change that value, this is not needed because the i value is only used in your function as a counter:

    const later = (milliseconds,value) =>
      new Promise(
        resolve=>
          setTimeout(
            ()=>resolve(value),
            milliseconds
          )
      );
    
    const countTo = toWhat => {
      const recur = counter =>
        later(1000,counter)
        .then(
          i=>{
            console.log(`i is now: ${i}`);
            return (iconsole.log(`i ended up at: ${i}`)
    );

提交回复
热议问题