手写一个Promise
手写一个Promise构造函数来实现promise的功能,能让我更加熟悉promise,加深对他的印象.
具体思路
- 在
new Promise2()
创建一个对象 - 将
getWeather
中的函数填入new Promise2()
中 - 这样一来,
Promise2
里的constructor
中的参数fn
就是getWeather
里的函数 - 然后执行
fn()
,fn()
里的参数就是用Promise2
构造函数创建的对象中的函数:resolve
和reject
.
class Promise2 {
state = 'pending'//设置初始状态
succeed = null
fail = null
constructor(fn){
fn(this.resolve.bind(this),this.reject.bind(this))
}
resolve(res){
setTimeout(()=>{
this.state = 'fulfilled'//当执行resolve时,将改变state放入任务队列中
this.succeed(res)
})}
reject(err){
setTimeout(()=>{
this.state = 'rejected'//当执行resolve时,将改变state放入任务队列中
this.fail(err)})
}
//之后会在then()中设置函数,把设置的函数复制到对象中,然后上面的resolve和reject就可以执行then()中的函数了
then(succeed,fail){
this.succeed = succeed
this.fail = fail
}
}
//设置一个函数,放进构造函数的参数里.
//构造函数中的函数,作为参数放进这个函数中.执行这个函数.
const getWeather = city => new Promise2((resolve,reject)=>{
let xhr = new XMLHttpRequest()
xhr.open('GET','http://rap2.taobao.org:38080/app/mock/245421/getWeather?city='+city,true)
xhr.onload =() => {
if(xhr.status === 200){
resolve(JSON.parse(xhr.responseText))
}else{
reject('大失败')
}}
xhr.send()})
getWeather('杭州').then(data => console.log(data),err => console.log(err))