Calling promise in another promise, conditionally
<p>This is basically my code, using <a href="https://github.com/kriskowal/q" rel="nofollow">q</a>:</p>

<pre><code>let d = Q.defer();
let result = {
    name: 'peter'
};

d.resolve(result);
return d.promise;
</code></pre>

<p>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.</p>

<p>Something like this:</p>

<pre><code>let d = Q.defer();
let result = {
    name: 'peter'
};

if (someParameter) {
    otherService.getValue() // Let's say it returns 'mary'
        .then((res) =&gt; {
            result.name = res;
        });
}

d.resolve(result);
return d.promise;
</code></pre>

<p>This doesn't work however (the <code>name</code> property is still 'peter'). Probably due to the fact that my inner promise is resolved at a later moment?</p>

<p>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:</p>

<pre><code>let d = Q.defer();
let result = {
    name: 'peter'
};

d.resolve(result);
return d.promise
    .then((data) =&gt; {
        if (someParameter) {
            // Works
            data.name = 'john';

            // Doesn't work
            otherService.getValue()
                .then((res) =&gt; {
                    data.name = res;
                });
        }

        return data;
    });
</code></pre>

<p>Here the name will be 'john', not 'mary'.</p>

<p>Clearly I'm misunderstanding promises, but I can't wrap my head around it.</p>