Reputation: 2189
I googled some bind explanation but still very confused. I am using bind with promise in the following way. It's working, but I don't know why. Hope someone could explain and help me with a small issue I got. Here is the sample code:
var temp1 = function(){
return new Promise(function(resolve, reject){
resolve("hello");
});
};
var temp2 = function(para1, para2){
console.log("1:", para1);
console.log("2:", para2)
return new Promise(function(resolve, reject){
resolve(para1+" "+para2);
});
};
temp1().then(temp2.bind(null,"world")).then(function(out){
console.log(out);
});
Output:
1: world \ 2: hello \ world hello \
I use "bind" because it can make the code cleaner and easier for error handling, otherwise I have to use the following:
temp1().then(function(out1){
return temp2(out1, "world").then(function(out2){
console.log(out2);
});
});
Besides how bind works, I have the following question:
temp1().then(temp2.bind(null,/*the second param is a property of the output from temp1*/)).then(function(out){
console.log(out);
});
I know I can always break the chain or add additional chain to achieve it: for example
temp1().then(function(out1){
return temp2(out1, (out1.length).to_String()).then(function(out2){
console.log(out2);
});
});
But it would be awesome not to break the chain.
So my two questions: 1. how bind works, 2. how to keep the chain(also no additional chain) while I can still access the previous output's properties in the params of next function inside then. Thanks!
Upvotes: 0
Views: 1663
Reputation: 956
bind()
is used to set the appropriate context for a function to be called later. I don't think you need to use it in this scenario. If you are using es6
you can do something like so:
temp1()
.then(out1 => temp2(out1, out1.length.toString()))
.then(console.log)
.catch(console.log);
This uses an implicit return. This works because temp2()
also returns a promsie so we can chain it to the next promise resolver
Upvotes: 0
Reputation: 819
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.
So technically, temp2.bind(null,"world")
will return a function and pass null,"world"
as parameter. Then, those parameters are merged with the result of temp1
which is "hello"
at index 0
. Therefore, the actual parameters are passed to temp2 are "hello", "world"
.
To keep the chain you can write:
temp1()
.then(function (out) {
return temp2(out,"world")
})
.then(function(out){
console.log(out);
});
This is why people created Promise so that you can chain them nicely. The example you gave works but it is similar to Callback Hell.
Upvotes: 1