What's difference between promise then and binding in AngularJS? [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I am wondering what is difference between those two services in AngularJS. In both there is promise and basicly both works.
Method with self variable:
module.exports = function () {
var self = this,
data = false;
self.someFunction = function () {
methodFromAnotherService().then(function (reponse) {
data = response;
});
};
};
Method with binding:
module.exports = function () {
var data = false;
this.someFunction = function () {
methodFromAnotherService().then(function (reponse) {
data = response;
}.bind(this));
};
};
The secound one doesn't work without binding. I know that this have something to do with scope. Please provide any usefull information about major differences.

The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Related

JavaScript - Using "this" with chained promises [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
I am writing some Node code with ES6. In my code, I have a class, that looks like the following. Please note, this is a basic example intended to isolate and show the problem.
class MyClass {
constructor() {
this.id = uuid();
this.number = Math.floor((Math.random() * 100) + 1);
}
process() {
this.validateNumber()
.then(this.generateImage)
.catch(function(err) {
console.log(err);
})
;
}
validateNumber() {
let self = this;
var promise = new Promise(function(resolve, reject) {
// do stuff with self.number
resolve({});
});
}
generateImage() {
console.log(this);
// the above prints "undefined" in the console window
// how do I get this.number again?
}
}
In this class, you'll notice that I generate a random number in my constructor. I want that number to be usable throughout the methods in my class. However, since I have one method that chains together promises, it's like this loses meaning after validateNumber is executed.
how do I resolve this?
ES6 introduced a feature called arrow functions. Apart from the syntax being more concise than the conventional function syntax, it retains the context of this. Essentially, your code can be changed to the following:
var promise = new Promise((resolve, reject) => {
console.log(this); // MyClass
resolve({});
});
And you also need to retain the context inside the then
this.validateNumber()
.then(() => this.generateImage());

Method called by other method with setInterval can not access object property in js [duplicate]

This question already has an answer here:
passing this.method in setTimeout doesn't work?
(1 answer)
Closed 7 years ago.
I wrote a object constructor function with two methods, one of them calls the other via setInterval(functionName, interval), and the called function fails to get the objects properties.
I wrote a simple example on codepen: http://codepen.io/AttilaVM/pen/ZQPVEy
function Test(value) {
this.value = value
this.action = function testAction() {
console.log(this.value); // gives undefined!
}
this.play = function testPlay() {
setInterval(this.action, 500);
}
}
var test = new Test(20);
test.play();
If the method is called without setInterval it works as expected. Why is it different? How can the called method access the object's properties?
this refers to window as it is being call in setInterval(window.setInterval)
To pass the current context, Use .bind(this), The bind() method creates a new function that, when called, has its this keyword set to the provided value
function Test(value) {
this.value = value
this.action = function testAction() {
console.log(this.value);
}
this.play = function testPlay() {
setInterval(this.action.bind(this), 500);
}
}
var test = new Test(20);
test.play();

Angular get/set variable on scope with this from function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I am adapting a controller to the "controller as" syntax.
But while transforming the code, I remarked that I can't access the "scope" variables with this out of a function.
If I understand the concept of this, then this does access the object it is used in.
As example this code:
this.scopeVariable = undefined;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
this.scopeVariable = result.foo;
});
};
So when I try to set the scopeVariable with this, I actually try to access an object from fooFunction, right?
If this is the case, how can I grab an object outside of the function within the function?
Thanks for your answers!
You have this problem because the this keyword changes definition when in a different scope. That means that if you have a simple object e.g.
var a = {
b: function() {
console.log(this); // => will log the value of "a"
setTimeout(function() {
console.log('just some rubbish');
console.log(this); // => will log inner function scope instead of "a"
}, 200)
}
}
a.b(); // to see the results
To prevent this issue from happening you can reassign this to a variable which will stay intact through deeper scopes like this:
this.scopeVariable = undefined;
var self = this;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
// using self. instead of this. makes the difference here
self.scopeVariable = result.foo;
});
};
Capturing the this being the scope in a variable: var that = this:
var that = this;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
that.scopeVariable = result.foo;
});
};

More elegant way to call method from ajax callback function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
I have a problem with javascript namespaces.
I want to call secondMethod from ajax callback function but I don't know how to get reference to it.
I have done it like that yet. But variable thisReference seems to me awkward. And whole construction is difficult to read.
So I'm writing there for help and answer how to rewrite it better.
var testObject = new TestObject();
testObject.firstMethod("hello world!");
function TestObject() {
var thisReference = this;
this.firstMethod = function(firstParam) {
ajaxFunc(firstParam, function(ajaxResult) {
thisReference.secondMethod(ajaxResult);
});
};
this.secondMethod = function(secondParam) {
alert("secondMethod " + secondParam);
};
}
function ajaxFunc(hello, callBack) {
callBack(hello);
}
Thanks a lot.
Ondra
Something like what you're doing is a common way to do it. Using:
var that = this;
or:
var self = this;
are common names to keep a hold of your original scope.
Another option (which I prefer) is to bind the this object to the method you're calling so that you have access to it in the callback. That would look like this:
this.firstMethod = function(firstParam) {
ajaxFunc(firstParam, function(ajaxResult) {
this.secondMethod(ajaxResult);
}.bind(this));
};
Hope that helps.

Supplying a callback and the context within which it is to be run [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 9 years ago.
myFn performs an async task and calls the callback on success
SearchController.prototype.show = function (query) {
this.searchService.myFn(arg1, this.myCallback); //I want to maintain this `this`
};
SearchController.prototype.myCallback = function (err, result) {
if(err) {
this.onError(err);
return;
}
this.onSuccess(result);
}
SearchController.prototype.onSuccess = function() {...)
SearchController.prototype.onError = function() {...)
Clearly the meaning of this is lost in the callback. How can I maintain this to be the this from the invocation of myFn?
It should be the responsibility of the myFn function to accept a context as parameter and then use it, or rewrite the method signature and wrap your call in an anonymous function that use call Function.prototype.call:
SearchController.prototype.show = function (query)
{
var __this = this;
this.searchService.myFn(function (){ __this.myCallback.call(__this, arg1); });
};
Here is how I would like to see myFn:
SearchController.prototype.myFn = function (arg, callback, context)
{
// Do work.. when finished:
callback.call(context, arg);
};
If you're having multiple args you want to apply, then use Function.prototype.apply.

Categories