Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Promise Declaration Difference

Tags:

javascript

I am a JavaScript learner and have an issue about Promises.

When I use function resolve of Promise object, I got no errors as expected. Like :

var promise1 = Promise.resolve(3);

However, when I use following declaration:

var promise2 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 1000, 'foo');
});
promise2.resolve(4)

Isn't this the same thing? Or if promise2 is also a Promise class object, why do I get an error like :

TypeError: promise2.resolve is not a function
    at Object.<anonymous>
like image 557
I.K. Avatar asked Nov 22 '25 14:11

I.K.


1 Answers

No, they are not the same thing.

The resolve method on the Promise (with a capital P) constructor function creates a new promise and immediately resolves it.

Existing promises don't have a resolve method. They can only be resolved by calling the function passed to the first argument of the function you pass to the Promise constructor function.


Or if promise2 is also a Promise class object, why do I get an error like

promise2 is an instance of Promise.

Promise is a constructor function used to create promises, it isn't a promise itself.

Consider the difference between a motor car and a Ford factory.

like image 84
Quentin Avatar answered Nov 24 '25 03:11

Quentin