zoukankan      html  css  js  c++  java
  • promise 理解

    对promise 的一些见解,

    1.Promise是一种为了避免回调地狱的异步解决方案
    2.Promise是一种状态机:

    pending(进行中)、fulfilled(已成功)和rejected(已失败)
    只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。

    3.Promise暴露的API
    .then(函数1,函数2)

    函数1:表示成功返回
    函数2:代表失败返回

    例如:

    promise.then(function(value) {
    // success
    }, function(error) {
    // failure
    });
    .catch:失败处理

    ajax(url,'GET') //通常成功返回的处理 .then(res=>{ console.log('获取数据::',res) }) //失败处理 .catch(error=>{ console.log('失败的处理',error) })

    .all:主要用于同时处理多个接口的请求时使用,只有多个接口同时成功返回时才可以

    Promise.all([p1(),p2()])
    .then(result=>{
    //其中result返回的是一个数组
    console.log('result:',result);
    });
    .finally:无论成功和失败,都会被执行

    .race:请求多个接口时,只要有一个状态改变,就会提前返回

    Promise.race([p2(),p1()]) .then(result=>{

    console.log('result:',result);
    })


    //完整版本:ajax封装
    function ajax(url = '', data = {}, type = 'GET', method = 'fetch') => {
    type = type.toUpperCase();
    url = baseUrl + url;

    if (type == 'GET') { //?id=1001&name=alice {id:1001,name:'alice'}
    let dataStr = ''; //数据拼接字符串
    Object.keys(data).forEach(key => {
    dataStr += key + '=' + data[key] + '&';
    })

    if (dataStr !== '') {
    dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
    url = url + '?' + dataStr;
    }
    }

    if (window.fetch && method == 'fetch') {
    let requestConfig = {
    credentials: 'include',
    method: type,
    headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
    },
    mode: "cors",
    cache: "force-cache"
    }

    if (type == 'POST') {
    Object.defineProperty(requestConfig, 'body', {
    value: JSON.stringify(data)
    })
    }

    try {
    const response = await fetch(url, requestConfig);
    const responseJson = await response.json();
    return responseJson
    } catch (error) {
    throw new Error(error)
    }
    } else {
    return new Promise((resolve, reject) => {
    let requestObj;
    if (window.XMLHttpRequest) {
    requestObj = new XMLHttpRequest();
    } else {
    requestObj = new ActiveXObject;
    }

    let sendData = '';
    if (type == 'POST') {
    sendData = JSON.stringify(data);
    }

    requestObj.open(type, url, true);
    requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    requestObj.send(sendData);

    requestObj.onreadystatechange = () => {
    if (requestObj.readyState == 4) {
    if (requestObj.status == 200) {
    let obj = requestObj.response
    if (typeof obj !== 'object') {
    obj = JSON.parse(obj);
    }
    resolve(obj)
    } else {
    reject(requestObj)
    }
    }
    }
    })
    }
    }

  • 相关阅读:
    Mongodb在window上启动
    java:JQuery(Ajax,JSON)
    SqlServer:SqlServer(sql,游标,定时作业,行转列,列转行,公用表达式递归,merge合并)
    java:WebService
    java:svn
    java:Echarts,POI
    java:LeakFilling(Other)
    java:activiti(工作流简介 )
    Linux:lvm磁盘分区,动态扩容
    java:dubbo
  • 原文地址:https://www.cnblogs.com/mzj143/p/12879070.html
Copyright © 2011-2022 走看看