0

Suppose I have scenario like this:

  1. Make request to post some data inside promise;
  2. a) If response data is ok - finish Promise+then chain;

    b) If response data is not ok - make new Promise+then chain - go back to point #2.

and code like this

var _p;
function make_promise(){
    return new Promise(function(resolve, reject){
        //get data 
        var data = 'some data';
        resolve(data);
    })
}


function handle_response(data) {
    var _p;
    if (data == 'some data'){
        console.log(data);
        //finish then chain
    }
    if (data != 'some data') {
        _p = make_promise()
            .then(handle_response);
    }
}

_p = make_promise()
    .then(handle_respone);

On each iteration when flow of execution goes on b) choise this code will create new promise inside handle_response function. Will this new promise replace old or it will saved in closure? If new promise will be saved in closure how to avoid this? Not save new promise to _p variable?

Raf
  • 622
  • 9
  • 19

1 Answers1

0

I think what you're actually looking for is

function getResponse() {
    return make_promise().then(function handle_response(data) {
        if (data == 'some data'){
            console.log(data);
            //finish then chain
        } else {
            return getResponse(); // repeat, recursively
        }
    }
}

var p = getResponse();

The imporant part is the return which makes the returned promise resolve with the result of the recursive call - that is, p will always only fulfill when the "chain" is "finished".

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Recursive call also stores the data for each call, and consume memory. If we have a few calls it is all good but if we must make significant amount of calls this is not an option. – Raf Aug 01 '15 at 08:04
  • @Raf: What do you mean by "stores data for each call"? Notice that `handle_response` is asynchronous, and that it's tail-recursive so no additional memory is consumed. – Bergi Aug 01 '15 at 08:55
  • I don't know what data is stored, I just make simple test, which show memory consumed. http://i.imgur.com/tjIOsT9.png?1 And of course 10000 calls it's not real work case. Just want to know how it works. – Raf Aug 01 '15 at 09:37
  • What promise implementation are you using? Of course every execution of code does consume memory, but [this pattern should not leak](http://stackoverflow.com/a/29931657/1048572). – Bergi Aug 01 '15 at 11:14
  • Native Promise inside Google Chrome 44.0.2403.125 (64-bit) – Raf Aug 01 '15 at 14:54