Reputation: 664
I've been having trouble with the behaviour of "then" not being waited for which I understand the reason for. However, I still need to get around it. Here is the use-case I'm having.
doWork(family) {
return doWork1(family)
.then(resultOfWork1 => doWork2(resultOfWork1));
}
doWork1(family) {
if (1 === family) {
return doFamily1();
} else {
return doFamily2();
}
}
doFamily1() {
return $http(urlToFamily1)
.then(response => parseFamily1Result(response));
}
parseFamily1Result(response) {
return parsed response in a family1 way;
}
doFamily2() {
return $http(urlToFamily2)
.then(response => parseFamily2Result(response));
}
parseFamily2Result(response) {
return parsed response in a family2 way;
}
doWork2(resultOfWork1) {
// use resultOfWork1
}
The issue in what I'm doing is that in doWork2, resultOfWork1 is undefined since the "then" promise isn't necessary executed before reaching doWork2.
Is there any way to ensure the fulfilment of "then"? Or is there something wrong with this way of doing things?
Upvotes: 0
Views: 66
Reputation: 3348
Your problem is not the promise chaining. It's simply because your resultOfWork1 never gets set, because you don't return anything in your doFamilyX functions.
doWork(family) {
return doWork1(family)
.then(resultOfWork1 => doWork2(resultOfWork1));
}
doWork1(family) {
if (1 === family) {
return doFamily1();
} else {
return doFamily2();
}
}
doFamily1() {
return $http(urlToFamily1)
.then(response => return parseFamily1Result(response)); //return the result
}
parseFamily1Result(response) {
return parsed response in a family1 way;
}
doFamily2() {
return $http(urlToFamily2)
.then(response => return parseFamily2Result(response)); //return the result
}
parseFamily2Result(response) {
return parsed response in a family2 way;
}
doWork2(resultOfWork1) {
// use resultOfWork1
}
Now your resultOfWork1 argument should be set to the value returned by parseFamilyXResult.
Upvotes: 0
Reputation: 3173
You have chained promises incorrectly.
Instead of
doWork(family) {
return doWork1(family)
.then(doWork2(resultOfWork1));
}
change it to
doWork(family) {
return doWork1(family)
.then(function(resultOfWork1){ doWork2(resultOfWork1); });
}
OR
doWork(family) {
return doWork1(family)
.then(doWork2);
}
You need to do similar changes for the following code as well.
$http(urlToFamily1)
.then(parseFamily1Result(response));
$http(urlToFamily2)
.then(parseFamily2Result(response));
Upvotes: 1