The Promise()
constructor only takes resolve
and reject
methods. How do you create a Promise
that takes parameters?
Asked
Active
Viewed 72 times
0

serv-inc
- 35,772
- 9
- 166
- 188
-
You don't want to create a promise, which is just a plain non-callable object. You want to create *a function* which may return a promise. – Bergi Aug 03 '19 at 09:37
1 Answers
0
The example at https://developers.google.com/web/fundamentals/primers/promises does this using closures. It creates a function that returns a Promise. The Promise uses the function's parameter via closure.
function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}

serv-inc
- 35,772
- 9
- 166
- 188