Reputation: 2425
I am reading this documentation about how to use promises, and frequently "resolve" and "reject" are passed in as arguments to the Promise constructor, even though nobody ever defined the "resolve" or "reject" functions. How is that possible? Don't we have to define functions before using them?
Here's an example: (source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Browser_compatibility)
var p1 = new Promise(
// The resolver function is called with the ability to resolve or
// reject the promise
function(resolve, reject) {
log.insertAdjacentHTML('beforeend', thisPromiseCount +
') Promise started (<small>Async code started</small>)<br/>');
// This only is an example to create asynchronism
window.setTimeout(
function() {
// We fulfill the promise !
resolve(thisPromiseCount);
}, Math.random() * 2000 + 1000);
});
Upvotes: 1
Views: 125
Reputation: 664503
They are not passed in as arguments to the Promise
constructor.
They are passed as arguments by the Promise
constructor into your resolver
callback function that declares them as parameters.
This is similar to the parameters of other callbacks, for example
array.sort(function(a, b) { … })
// ^ ^
array.map(function(element, index) { … })
// ^^^^^^^ ^^^^^
only that the values are functions in the case of the Promise
constructor callback.
Upvotes: 1