zoukankan      html  css  js  c++  java
  • promise.js代码分析

    一、promise chain(可以用以下方式,替代使用在扑捉异常错误,多个if else判断)

       PS:function taskA() 里 增加 “throw new Error("throw Error @ Task A")”,则onRejected(error)打印出日志。

    Build Status

    来源:http://liubin.github.io/promises-book/#chapter2-how-to-write-promise

    二、Promise对象实现Ajax操作:

    var getJSON = function(url) {
        var promise = new Promise(function(resolve, reject){
    var client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();

    function handler() {
    if (this.readyState!== 4) {
    return;
    }
    if (this.status === 200) {
    resolve(this.response);
    }
    else {
    reject(new Error(this.statusText));
    }
    };
    });
    return promise;
    };
    getJSON("/posts.json").then(function(json)
    {
    console.log('Contents: ' + json);
    },
    function(error) {
    console.error('出错了', error);
    }
    );
    
    
  • 相关阅读:
    linux初学者-普通磁盘分区篇
    linux初学者-延迟及定时任务篇
    linux初学者-网络管理篇
    linux初学者-虚拟机联网篇
    贪吃蛇Ground Java实现(二)
    贪吃蛇 Java实现(一)
    创建异常
    IO流
    实训第一天
    Array 遍历数组
  • 原文地址:https://www.cnblogs.com/babyfacer/p/4721407.html
Copyright © 2011-2022 走看看