// version 1 callback
function helloPromise(callback) {
setTimeout(() => {
// 计算密集型程序 或者 IO类型 的操作
// ajax
callback({code: 200, data: '123', msg: 'message'});
}, 1000)
}
helloPromise((result) => {
console.log(result);
})
// promise es6+
// // version 2 自定义简易 promise
// class MyPromise {
// thenFunc = null
// catchFunc = null
// finallyFunc = null
// constructor(func) {
// func((data) => {
// this.thenFunc(data)
// this.finallyFunc()
// }, (error) => {
// this.catchFunc(error)
// this.finallyFunc()
// })
// }
// // 需要返回Promise对象
// then(func) {
// this.thenFunc = func
// return this;
// }
// // 需要返回Promise对象
// catch(func) {
// this.catchFunc = func
// return this;
// }
// // 返回void
// finally(func) {
// this.finallyFunc = func
// }
// }
// new MyPromise((resolve, reject) => {
// setTimeout(() => {
// resolve()
// }, 1000)
// })
// .then(() => {
// console.log('我是在成功的时候才会执行的函数.')
// })
// .catch(() => {
// console.log('我是在失败的时候会执行的函数.')
// })
// .finally(() => {
// console.log('我是始终都会执行的函数.')
// })
// // version 3 promise api
// function helloPromise() {
// return new Promise((resolve) => {
// setTimeout(() => {
// resolve('hello promise')
// }, 1000)
// })
// }
// helloPromise()
// .then(result => {
// console.log(result)
// return '我是then返回的数据'
// })
// .then((result) => {
// console.log(result)
// })
// .catch(() => {
// console.log('我是失败会调用的函数.')
// })
// .finally(() => {
// console.log('我是不管成功还是失败都会执行的函数')
// })