3

I am calling a method a which is returning a promise and inside it I am calling a method which do some operation and update the count variable. I want all the promise get finish once the count is done but it is not stopping after reaching the value 10.

  var count = 0;

  function a(p){
   return new Promise((resolve, reject) =>{
    console.log(count);
    if(count == 10) {console.log('sdfsdfsd'); resolve(Date.now()); }

    callee().then(() => { count++; a(); } )
  })
 }

 function callee(){ return new Promise((resolve) => resolve())}

 a(1).then((res) => console.log(res)).catch((res) => console.log(res));
Sachin
  • 2,912
  • 16
  • 25
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! `callee` should be the only function using `new Promise` – Bergi Jan 06 '19 at 21:31
  • @Bergi I just replicated the actual scenerio using Promise, In actual code I have two async http calls. – Sachin Jan 07 '19 at 05:34
  • Yes, then do that in `callee`. The point is that `a` should not use `new Promise` - see @adz5A's working answer – Bergi Jan 07 '19 at 07:27

2 Answers2

2
// So you have a function `foo` which returns a promise eventually resolved, you want to write a function
// `bar` that will call this function n times, waitinng between each call for the returned promise to be
// resolved. This function will itself return a promise

// this function returns a promise which is resolved after one second
const foo = () => new Promise(resolve => setTimeout(resolve, 1000));

// Recursively call the foo function until 0 is reached.
// This will actually create a chain of promises which settle after one second.
// It also uses the fact that if you return a promise `a` in the `then` handler the returned
// promise `b` will only settle when `a` is resolved.
const bar = n => {
    if (n === 0) return Promise.resolve();

    return foo().then(() => bar(n-1));
};

bar(10).then(() => console.log("done"));
adz5A
  • 2,012
  • 9
  • 10
1

var count = 0;

function a(p) {
    return new Promise((resolve, reject) => {
        console.log(count);
        if (count == 10) { console.log('sdfsdfsd'); return resolve(Date.now()); }

        return callee().then(() => {
            count++;
            return resolve(a());
        })
    })
}

function callee() { return new Promise((resolve) => resolve()) }

a(1).then((res) => console.log("res",res)).catch((res) => console.log(res))
Vadim Hulevich
  • 1,803
  • 8
  • 17