Promise简单实现XHR异步请求数据

84 阅读1分钟
                const promise = new Promise(function(resolve,rejcet){
                    const handler = function(){
                        if(this.readyState !== 4 ){
                            return
                        }
                        if(this.readyState === 200){
                            resolve(this.response)
                        }else{
                            rejcet(new Error(this.statusText))
                        }
                    }
                    const client = new XMLHttpRequest()
                    client.open('GET',url)
                    client.onreadystatechange = handler
                    client.responseType = 'json'
                    client.setRequestHeader('Accept','application/json')
                    client.send()
                })
                return promise
            }

            getJSON('/posts.json').then( function(json){
                console.log('Contents:'+json);
            },function(error){
                console.log('出错了',error);
            })