- ES6的promise的語言標準。promise/A+規(guī)范
2.如何使用
3.場景逐哈。
promiseObj.then(onFulfilled,onRejected);
onFulfilled=function(value){
return promiseObj2
}
onRejected=function(err){}
簡單理解例子:
var getJSON = function (url) {
var promise = new Promise(function (resolve, reject) {
function handler() {
if (this.state === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
}
});
return promise;
};
//場景一
getJSON('/posts.json').then(function (json) {
console.log('Content' + json);
}, function (error) {
console.error('error');
});
//場景二
getJSON('/posts.json').then(function (json) {
return json.post;
}).then(function (post) {
});
//場景三
getJSON('/posts.json').then(
post => getJSON(post.commentURL)
).then(
comments => console.log('comments'),
err => console.log('rejected', err)
);
getJSON('/posts.json').then(function (post) {
getJSON(post.commentURL);
}
).then(function(comments){
console.log();
},function(err){
console.err();
});
//catch 最好用catch去捕獲異常芬迄。