ES6 - Promise 实现原理 2019-03-01- 2022-01-05 Javascript > ES6-ES6Promise12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061global.Promise = (function () { class Promise { constructor(callback) { this.val = undefined; this.status = "pending"; this.init(callback); } onReject = (err) => { this.val = err; this.status = "reject"; console.log("onReject is call"); }; onResolve = (val) => { this.val = val; this.status = "fulfilled"; console.log("onResolve is call"); }; init(callback) { callback(this.onResolve, this.onReject); } then(resolve, reject) { if (this.status === "fulfilled") { resolve(this.val); } else if (this.status === "reject") { if (!reject === undefined) reject(this.val); } return this; } finally(cb) { if (this.status === "fulfilled" || this.status === "reject") { cb(); } } catch(cb) { cb(this.val); return this; } } Promise.reject = function () {}; Promise.resolve = function () {}; return Promise;})();function getApi(flag = true) { return new Promise((resolve, reject) => { if (flag) { resolve(123); } else { reject(new Error("你错了!")); } });}getApi(true) .then((res) => { console.log(res); return 123; }) .then((val) => { console.log(val); }); I'm so cute. Please give me money.Post author: 彩鹏Post link: https://blog.gaocaipeng.com/2019/03/01/sfy1ld/Copyright Notice: All articles in this blog are licensed under unless otherwise stated.