Bind the scope of the "this" promise callback function

Usually, if you are not using promises, you can easily do

var a = function(cb){ setTimeout(function(){ var boundCb = cb.bind({hello: 'world'}); boundCb(); }, 100); }; a(function(){ alert(this.hello); }); 

which is not particularly useful in most cases (since you can pass the same things as regular arguments), but it allows you to use some extremely readable codes and / or easy-to-use interfaces.

When switching to promises, however, it becomes much more complicated. Unsurprisingly, the following does not work (since resolve not a direct link)

 var a = function(){ return new Promise(function(resolve, reject){ var boundResolve = resolve.bind({hello: 'word'}); boundResolve(); }); }; a().then(function(){ alert(this.hello) }); 

so is it even possible to achieve this?


Optional postscript: "Fortunately" in my situation, the this region that I want to set already matches the this region in a() . So I am currently just writing .bind(this) after each Promise callback function, and in the future I will be able to use arrow functions for this, but at the same time I am looking for a cleaner solution.

+5
source share
1 answer

Native Promises do not offer this feature. However, the Bluebird Promise library offers Promise.prototype.bind

Here is a usage example

 MyClass.prototype.method = function() { return fs.readFileAsync(this.file) .bind(this) .then(function(contents) { var url = urlParse(contents); return this.httpGetAsync(url); // this is bound to the MyClass instance }).then(function(result) { // this is still bound, further down the chain. var refined = this.refine(result); return this.writeRefinedAsync(refined); }).catch(function(e) { this.error(e.stack); // Even in event handlers }); }; 
+4
source

Source: https://habr.com/ru/post/1246621/


All Articles