ng.newbie
ng.newbie

Reputation: 3226

Cannot understand why outer Promise wont resolve

I am a beginner to the weird ways Javascript works, and I am unable to understand the single threaded design and how Promises work.

Take the following code:

function a() {
  return new Promise((resolve, reject) => {
 		var inn = new Promise((resolve, reject) => {
          setTimeout(() => reject('Error'), 0);
        }).catch((msg) => console.log(msg));
    return inn;
  });
}

a().then((msg) => console.log('then'));

My questions are the following:

Sorry if this is noob but I am unable to exactly find the answers that I looking for, most other posts are just confusing me.

Upvotes: 1

Views: 80

Answers (3)

t.niese
t.niese

Reputation: 40882

Using new Promise within another new Promise is an antipattern, and what you experience here is a reason why.

You don't call any of the resolve and reject of the outer new Promise. The return inn has no effect, because the outer new Promise is only resolved or rejected, by either calling resolve, reject or by an error that is thrown, and neither of this is happening there.

That's how it should look like:

function a() {
  return new Promise((resolve, reject) => {
    setTimeout(() => reject('Error'), 0);
  }).catch((msg) => console.log(msg));
}

a().then((msg) => console.log('then'));

You only use new Promise if you need to convert something async that does not provide a Promise as a result, into a Promise. And you want to keep the code footprint within that new Promise as small as possible, so that you can be sure that every code path will lead to either a resolve ar reject condition.

So turning a setTimeout into a Promise by wrapping it into a new Promise is fine. But at that point, you have a Promise, so there is no need to wrap that into another new Promise. That breaks the whole purpose of chaining and the guarantees Promises make. (What is the explicit promise construction antipattern and how do I avoid it?)

And you should not use strings as errors. Neither for throw nor for reject use reject(new Error('Error')) (or a custom error object) instead.

Upvotes: 1

Aditya Bhave
Aditya Bhave

Reputation: 1028

Because first promise is not resolved/rejected. Check following. I just changed return inn to resolve(inn)

function a() {
  return new Promise((resolve, reject) => {
 		var inn = new Promise((resolve, reject) => {
          setTimeout(() => reject('Error'), 0);
        }).catch((msg) => console.log(msg));
    resolve(inn);
  });
}

a().then((msg) => console.log('then'));

Upvotes: 0

pkfm
pkfm

Reputation: 461

You must resolve inn within function a rather than return it in order for the promise chain to continue unbroken.

Upvotes: 0

Related Questions