Promise常规写法
let promise = new Promise((resolve, reject)=>{ //做一些异步操作 setTimeout(function () { resolve("成功"); }, 1000); setTimeout(function () { reject("失败"); }, 2000); }); promise.then(d => { console.log(d); }).catch(d => { console.log(d); }); //输出“成功”
JavaScript(ES5)实现
var promise = function (__then, __catch) { var _done = false;//记录是否已经执行了回调函数 //做一些异步操作 setTimeout(function () { _done || __then && __then("成功"),_done = true; }, 1000); setTimeout(function () { _done || __catch && __catch("失败"), _done = true; }, 2000); }; promise(function(d) { console.log(d); }, function(d) { console.log(d); }); //输出“成功”