promise = new Promise(function(){})
var promise = new Promise(function(resolve, reject) {
//first execute
if (/* 如first execute成功 */){
resolve(value);//發出resolve
} else {
reject(error);發出reject
}
});
promise.then(function(value) {
// success//接收到resolve後會執行
}, function(value) {
// failure //接收到reject後會執行
});
function get(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
}
else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}
get('story.json').then(function(response) {
return JSON.parse(response);
}).then(function(response) {
console.log("Yey JSON!", response);
});