var p1 = new Promise(function(){}) //处于pending状态的Promise对象p1 var p2 = Promise.resolve(1) //处于fulfilled状态的p2 var p3 = Promise.reject('error') //处于reejected状态的p3
new Promise((resolve, reject) => { let v = Math.random() if(v > 0.5) { resolve(v) } else { reject('less than 0.5') } }).then(v => { console.log(v) }, reason => { console.error(reason) })
2.2.6
let p = new Promise(resolve => resolve(1)) p.then(v => console.log(v)) p.then(v => console.log(v))
then 必须返回一个promise,对于promise2 = promise1.then(onFulfilled, onRejected)
,如果 onFulfilled 或者 onRejected 返回一个值 x , 则运行 Promise 解决过程: [[Resolve]](promise2, x).
当x是一个普通值时 2.3.4
const delayer = (t) => new Promise((resolve, reject) => { setTimeout(() => { resolve(t) }, t) }) delayer(1000).then(t => { console.log(t) return t + 1000 //返回普通值 }).then(t => { console.log(t) console.log('end') })
当x是一个Promise对象时 2.3.2
delayer(1000).then(t => { console.log(t) return delayer(2000) }).then(t => { console.log(t) console.log('end') })
delayer(1000).then(t => { console.log(t) return Promise.resolve(2000) }).then(t => { console.log(t) console.log('end') })
当x是包含then方法的对象时 2.3.3
delayer(1000).then(t => { console.log(t) return { then(resolvePromise, rejectPromise ) { console.log('in then') resolvePromise(3000) //rejectPromise('eee') } } }).then(t => { console.log(t) console.log('end') }, e => { console.log('error') console.log(e) })