new Promise((resolve, reject) => {
setTimeout(() => {//什麼情況下執行,比方說接口請求成功
resolve({name:‘san‘});
}, 500);
})
.then(val => {//成功回調
console.log(val.name);//san
}, err => {
console.error(err);//报错
});
.........
new Promise((resolve, reject) => {
console.log(e);
})
.catch(err => {
console.log(‘error be rejected?‘, err);// 捕获内部错误
});
.........
链式调用
let p = new Promise((resolve, reject) => {
resolve(‘i am resolved‘);
})
.then(val => {
return val;
});
console.log(p);
在then中return的值又变成了promise对象。
p.then(val => {
console.log(val);// i am resolved
});
|
摘自 http://xixitoday.com/2017/09/30/promise/ 写的通俗易懂