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.
source share