// Promise.resolve() Promise.resolve(1).then((data) => { console.log(data) // 1 }) // Promise.reject() Promise.reject(2).catch((data) => { console.log(data) // 2 }) // Promise.all() // 多个Promise都成功后获取结果,调用成功回调,如果有一个promise失败了,all返回的promise对象也会失败,调用失败回调 Promise.all([1, new Promise((res, rej) => { res(10) })]).then((data) => { console.log(data) // [1, 10] }) // Promise.finally()不管上一个promise状态是什么 都会执行 Promise.resolve(111).finally((data) => { console.log(data) // undefined return 2; // return new Promise((resolve, reject) => { // reject('222') // }) }).then(data => { console.log(data) // 111 }).catch(reason => { console.log(reason) // finally中返回失败的promise才执行 }) // race 谁最快改变状态 就执行谁的回调 Promise.race([1,3]).then(data => { console.log(data) // 1 }).catch(err => console.log(data))
class MyPromise { static finally(callback) { return this.then(data => { // 直接调用callback()无法处理异步代码 Promise.resolve(callback()).then(() => data) }, err => { Promise.resolve(callback()).then(() => {throw err}) }) } static all(args) { let results = []; let promiseCount = 0; let promisesLength = promises.length; return new Promise(function(resolve, reject) { for (let val of promises) { // 将普通值也包装成promise来处理 Promise.resolve(val).then(function(res) { // 记录当前执行了几个promise promiseCount++; // 成功回调的参数存放到结果数组中 results[i] = res; // 当所有promise都为成功转态,在all返回的promise实例中调用resolve,传入结果数组。 if (promiseCount === promisesLength) { return resolve(results); } }, function(err) { return reject(err); }); } }); } static race(proms) { return new Promise((resolve, reject) => { proms.forEach((p) => { p.then( (data) => { resolve(data); }, (err) => { reject(err); }, ); }); }); } static resolve(data) { if (data instanceof Promise) { return data; } else { return new Promise((resolve) => { resolve(data); }); } } static reject(reason) { return new Promise((resolve, reject) => { reject(reason); }); } }