This is basically my code, using q:
let d = Q.defer();
let result = {
name: 'peter'
};
d.resolve(result);
return d.promise;
However, I now need to perform a step based on a certain condition. This step is calling another object that also returns a promise. So I'm having nested promises, if that's the correct term.
Something like this:
let d = Q.defer();
let result = {
name: 'peter'
};
if (someParameter) {
otherService.getValue() // Let's say it returns 'mary'
.then((res) => {
result.name = res;
});
}
d.resolve(result);
return d.promise;
This doesn't work however (the name
property is still 'peter'). Probably due to the fact that my inner promise is resolved at a later moment?
I've also tried this, but it doesn't work if I call the otherService which returns a promise. It does work if I just set the value:
let d = Q.defer();
let result = {
name: 'peter'
};
d.resolve(result);
return d.promise
.then((data) => {
if (someParameter) {
// Works
data.name = 'john';
// Doesn't work
otherService.getValue()
.then((res) => {
data.name = res;
});
}
return data;
});
Here the name will be 'john', not 'mary'.
Clearly I'm misunderstanding promises, but I can't wrap my head around it.