javascript - Prevent binding a function more than once -


i have recursive retry routine, this:

foo.prototype.retry = function(data, cb){     cb && (cb = cb.bind(this));  // want bind cb fn once     this.resolutions[x] = (err, val) => {        if(val === 'foobar'){         // in case, retry         return this.retry(data, cb);       }     }:  } 

as can see, under circumstances, retry calling this.run again. avoid calling cb.bind() more once. there way that?

=> mean, there way somehow check function bound this value?

the solution know of pass retry count, so:

 foo.prototype.retry = function(data, cb){         if(cb){          if(!data.__retrycount){              cb = cb.bind(this);          }        }         this.resolutions[x] = (err, val) => {            if(val === 'foobar'){             // retry here             data.__retrycount = data.__retrycount || 0;             data.__retrycount++;             return this.retry(data, cb);           }         }:      } 

you can use local variable bound version when call recursively, pass original cb, not bound one:

foo.prototype.run = function(data, cb){     let callback = (cb && cb.bind(this)) || function() {};     this.resolutions[x] = (err, val) => {       if(val === 'foobar'){         // retry here , pass original cb         return this.run(data, cb);       }    };     // elsewhere in function when want use bound one, use callback() } 

or, if want ever bind once, can in wrapper function , call recursively via sub-function assumes callback bound:

// internal function, assumes callback bound foo.prototype._run = function(data, cb){     // cb bound here     this.resolutions[x] = (err, val) => {         if(val === 'foobar'){         // retry here             return this._run(data, cb);         }    }  }  // bind callback , call our internal function foo.prototype.run = function(data, cb){    let callback = (cb && cb.bind(this)) || function() {};    return this._run(data, callback); } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -