Promise.resolve vs resolve

Hay, I have this code:

var promise1 = new Promise(function(resolve, reject) {
  setTimeout(() => {
         console.warn('Elo');
         resolve('First response');
      },
      1000);
})

promise1
.then((resp) => {
    console.warn('First then!');

});

And It resolves promise after one second going to then and console.warning 'First then!'.

But when I change line:

resolve('First response');

for

Promise.resolve('First response');

It won't work. Some idea why ?

Also tried

return Promise.resolve('First response');

But it also doesn't work. I don't know why.

Can you help me understand it?

Answers:

Answer

The new Promise constructor passes a specific function into your callback, which becomes your resolve parameter. That promise (the one you're constructing there with new Promise) can only be resolved by calling that specific resolve function.

Promise.resolve simply creates a new "pre-resolved" promise. It does not resolve any existing promise (nor would it have any way of knowing which promise it's supposed to resolve).

Answer

Another way to think about it is:

Resolve === resolveCallback === first argument provided to your Promise callback Promise.resolve === a function to returns a new Promise

These two are functional equivalents:

`const foo = Promise.resolve('First response').then( /* ... */ );`

`const bar = new Promise(function(resolveCallback, rejectCallback) {
    resolveCallback('First response');
  }).then( /* ... */ );`

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.