1. 當Promise對象作為resolve的參數時
const p = Promise.resolve(); const p1 = Promise.resolve(p); //就是p const p2 = new Promise(res => res(p)); //新建一個對象,對象狀態依賴p // res(p)可以看作 await p1; await resolve(); // 或者p.then(data => getData()).then(() => p2.resolve()) // 首先;p1 === p; p2!===p // 那么,p1是一個fulfilled狀態的對象;p2狀態需要運行后求得 console.log(p === p1); // true console.log(p === p2); // false p1.then(() => { console.log('p1-1'); }).then(() => { console.log('p1-2'); }).then(() => { console.log('p1-3'); }) p2.then(() => { //p2.resolve之后才能調用回調函數 console.log('p2-1'); }).then(() => { console.log('p2-2'); }).then(() => { console.log('p2-3'); }) p.then(() => { console.log('p-1'); }).then(() => { console.log('p-2'); }).then(() => { console.log('p-3'); }) // 運行結果 // getData() p1-1 p-1 // resolve() p1-2 p-2 p2-1 p1-3 p-3 p2-2 p2-3
2. 當Promise的resolve方法在另一個Promise對象的then方法中運行時,變異步;
let p3; p1 = new Promise(resolve => { p3 = new Promise(res => res()); p3.then(() => { console.log('p3') resolve(); // resolve()方法用在then方法中,變為異步執行 }) }) p1.then(() => { console.log('p1-1'); }).then(() => { console.log('p1-2'); }) p3.then(() => { console.log('p3-1') }).then(() => { console.log('p3-2') }) // 運行結果如下: p3 p3-1 p1-1 p3-2 p1-2
示例:
const p1 = Promise.resolve(); let p3; const p2 = new Promise(function(resolve, reject){ p3 = new Promise(res => res(p1)); p3.then(() => { //1 p3.then第一個 console.log('p3') resolve('ok'); }) }); p1.then(() => { console.log('p1-1') }).then(() => { console.log('p1-2') }).then(() => { console.log('p1-3') }) p2.then(function(data) { console.log('p2-1') }).then(function(data) { console.log('p2-2') }).then(function(data) { console.log('p2-3') }) // p3.then第二個,p3狀態變化觸發then方法時,同時觸發,按照先后順序執行 // 只要時p3.then(...)都同時觸發 p3.then(function(data) { console.log('p3-1') }).then(function(data) { console.log('p3-2') }).then(function(data) { console.log('p3-3') }) // 運行結果 p1-1 p1-2 p3 p3-1 p1-3 p2-1 p3-2 p2-2 p3-3 p2-3
3. 當使用catch()方法捕獲異常時
const p1 = Promise.resolve(); const p2 = Promise.reject(); //狀態為rejected p1.then(() => { console.log('p1-1') }).then(() => { console.log('p1-2') }).then(() => { console.log('p1-3') }) p2.then(function(data) { //會立即觸發,但是觸發的是then中省略的第二個函數; console.log('p2-1') }).then(function(data) { console.log('p2-2') }).then(function(data) { console.log('p2-3') }).catch(() => { console.log('catched') }) // 運行結果如下: p1-1 // 默認運行p2的第一個錯誤回調 p1-2 // 默認運行p2的第二個錯誤回調 p1-3 // 默認運行p2的第三個錯誤回調 catched
4. 當有async函數時
async function async1() { console.log('async1 start'); await async2(); //async()函數執行是同步調用;生成Promise后等待狀態改變返回結果是then任務 console.log('async1 end'); } async function async2() { console.log('async2'); } console.log('script start'); setTimeout(() => { console.log('setTimeout') }) async1(); new Promise((resolve, reject) => { console.log('promise1'); resolve(); }).then(() => { console.log('promise2'); }) // 運行結果如下 script start async1 start async2 promise1 async1 end promise2 setTimeout