zoukankan      html  css  js  c++  java
  • 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);
    

      

  • 相关阅读:
    数组方法总结
    CSS3总结
    关于h5的一些知识整理
    如何去掉iview里面的input,button等一系列标签自带的蓝色边框
    CSS隐藏多余的文字
    百度搜索之历史搜索记录~
    transform相关~
    有关数组的相关知识~~
    [Javascript]js中所学知识点回顾总结
    js_随即生成多位验证码及变换颜色
  • 原文地址:https://www.cnblogs.com/sunny666/p/12986651.html
Copyright © 2011-2022 走看看