12. Promise对象

是异步编程的一种解决方案。

从语法上说,Promise 是一个对象,从它可以获取异步操作的消息。

Promise 状态

状态的特点

  Promise 异步操作有三种状态:pending(进行中)、fulfilled(已成功)和 rejected(已失败)。除了异步操作的结果,任何其他操作都无法改变这个状态。

  Promise 对象只有:从 pending 变为 fulfilled 和从 pending 变为 rejected 的状态改变。只要处于 fulfilled 和 rejected ,状态就不会再变了即 resolved(已定型)。

let pro = new Promise(function(resolved,rejected) {
            //执行异步操作
            let res = {
                code: 201,
                data:{
                    name:'小马哥'
                },
                error:'失败了'
            }
            setTimeout(() => {
                if(res.code === 200){
                    resolved(res.data);
                }else{
                    rejected(res.error);
                }
            }, 1000);
        })
        console.log(pro);
        pro.then((val)=>{
            console.log(val);
            
        },(err)=>{
            console.log(err);
            //失败了'

});

then 方法

then 方法接收两个函数作为参数,第一个参数是 Promise 执行成功时的回调,第二个参数是 Promise 执行失败时的回调,两个函数只会有一个被调用。


封装异步请求回调函数

        // https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976
        const getJSON = function (url) {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', url);
                xhr.onreadystatechange = handler;
                xhr.responseType = 'json';
                xhr.setRequestHeader('Accept', 'application/json');
                // 发送
                xhr.send();

                function handler() {

                    if (this.readyState === 4) {
                        if (this.status === 200) {
                            resolve(this.response.HeWeather6);
                        } else {
                            reject(new Error(this.statusText));
                        }
                    }

                }
            })
        }
        let a = getJSON(
                'https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976')
            .then((data) => {
                console.log(data);
                return data[0]
            }).then((obj)=>{
                console.log(obj);

            })
        console.log(a);

  

原文地址:https://www.cnblogs.com/sunny666/p/12986651.html