I am confused with below simple Promise example.
Question 1: From the console log, why the resolve is executed after the console.log("200") statement?
Question 2: Enable the resolve() before onload() and make the GET request against with an invalid url. Even the AJAX returned with 404, the reject won't be called this time since the resolve before onload is called. Why won't reject be called ?
https://jsfiddle.net/tut5va0m/3/
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);
//Enable below for Question 2
//resolve(req.response);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
//Question 1
resolve(req.response);
console.log("200");
}
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();
});
}
function resolve(data) {
console.log("Success!!! " + data);
}
function reject(data) {
console.log("Fail!!! " + data);
}
var url = '/echo/json';
var invalidUrl = '/abc'
get(url).then(resolve, reject);
//below is for Question 2
get(invalidUrl).then(resolve, reject);