var doSomething = function() {
return new Promise((resolve, reject) => {
resolve('返回值');
});
};let doSomethingElse = function() {
return '新的值';
}doSomething().then(function () {
return doSomethingElse();
}).then(resp => {
console.warn(resp);
console.warn('1 =========<');
});doSomething().then(function () {
doSomethingElse();
}).then(resp => {
console.warn(resp);
console.warn('2 =========<');
});doSomething().then(doSomethingElse()).then(resp => {
console.warn(resp);
console.warn('3 =========<');
});doSomething().then(doSomethingElse).then(resp => {
console.warn(resp);
console.warn('4 =========<');
});
Promise.prototype.then
當Promise中的狀態(pending?--->?resolved?or?rejected)發生變化時才會執行then方法。
- 調用then返回的依舊是一個Promise實例 ( 所以才可以鏈式調用... )
new Promise((res, rej)=> {res('a');
}).then(val=> {return 'b';
});// 等同于
new Promise((res, rej)=> {res('a');
}).then(val=> {return new Promise((res, rej)=> {res('b');});
});
- then中的回調總會異步執行
new Promise((res, rej)=> {console.log('a');res('');
}).then(()=> {console.log('b');
});
console.log('c');
// a c b
- 如果你不在Promise的參數函數中調用resolve或者reject那么then方法永遠不會被觸發
new Promise((res, rej)=> {console.log('a');
}).then(()=> {console.log('b');
});
console.log('c');
// a c
Promise.resolve()
除了通過new Promise()的方式,我們還有兩種創建Promise對象的方法,Promise.resolve()相當于創建了一個立即resolve的對象。如下兩段代碼作用相同:
Promise.resolve('a');new Promise((res, rej)=> {res('a');
});
當然根據傳入的參數不同,Promise.resolve()也會做出不同的操作。
- 參數是一個 Promise 實例
如果參數是 Promise 實例,那么Promise.resolve將不做任何修改、原封不動地返回這個實例。
- 參數是一個thenable對象
thenable對象指的是具有then方法的對象,比如下面這個對象。
let thenable = {then: function(resolve, reject) {resolve(42);}
};
Promise.resolve方法會將這個對象轉為 Promise對象,然后就立即執行thenable對象的then方法。
- 參數不是具有then方法的對象,或根本就不是對象
如果參數是一個原始值,或者是一個不具有then方法的對象,則Promise.resolve方法返回一個新的 Promise 對象,狀態為resolved。
- 不帶有任何參數
Promise.resolve方法允許調用時不帶參數,直接返回一個resolved狀態的 Promise 對象。
class Man {constructor(name) {this.name = name;this.sayName();this.rope = Promise.resolve(); // 定義全局Promise作鏈式調用}sayName() {console.log(`hello, ${this.name}`);}sleep(time) {this.rope = this.rope.then(()=> {return new Promise((res, rej)=> {setTimeout(()=> {res();}, time*1000);});});return this;}eat(food) {this.rope = this.rope.then(()=> {console.log(`${this.name} eat ${food}`); });return this;}
}new Man('lan').sleep(3).eat('apple').sleep(5).eat('banana');
class Man1345 {constructor(name) {this.name = name;this.sayName(); }sayName() {console.log(`hello, ${this.name}`);}sleep(time) { this.rope = new Promise((res, rej)=> {setTimeout(()=> {res();}, time*1000);}); return this;}eat(food) {this.rope = this.rope.then(()=> { console.log(`${this.name} eat ${food}`); });return this;}
}new Man('lan').sleep(3).eat('apple').sleep(5).eat('banana');
// 第一段正確的代碼的執行為
var p1 = new Promise().then('停頓3s').then('打印食物').then('停頓5s').then('打印食物');// 第二段代碼的執行行為,p1、p2異步并行執行
var p1 = new Promise().then('停頓3s').then('打印食物');
var p2 = new Promise().then('停頓5s').then('打印食物');
Promise對象在創建即執行(new--關鍵字)
then(拿前面異步的返回值)

?