Inside the constructor Promise
- , - , , :
new Promise(function(resolve, reject){
setTimeout(function(){
}, 100);
});
API promises, , promises, , ( ).
then
. throw then, . , , , return, .
, Angular 1.x $q, - ( throw , ).
, promises. promises , - API promises :
class Request {
// other methods
send(method, url, args, body) {
return new Promise((res, rej) => { // it good that new Promise is the first
let xhr = new XMLHttpRequest(); // line since it throw-safe. This is why it
xhr.open(method, url); // was chosen for the API and not deferreds
xhr.onload = () => {
// This _needs_ a try/catch, it will fail if responseText
// is invalid JSON and will throw to the global scope instead of rejecting
res(JSON.parse(xhr.responseText));
};
xhr.onerror = () => {
let status = xhr.status;
switch (status) {
case 401:
// this _must_ be a reject, it should also generally be surrounded
// with a try/catch
rej(new UnauthorizedError(url));
}
};
xhr.send(); // it important that this is in the promise constructor
});
}
}