zoukankan      html  css  js  c++  java
  • promise链式

    var getJSON = function(url) {
      var promise = new RSVP.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 === this.DONE) {
            if (this.status === 200) { resolve(this.response); }
            else { reject(this); }
          }
        };
      });
    
      return promise;
    };
    
    getJSON("/posts.json").then(function(json) {
      // continue
    }, function(error) {
      // handle errors
    });

    Chaining

    One of the really awesome features of Promises/A+ promises are that they can be chained together. In other words, the return value of the first resolve handler will be passed to the second resolve handler.

    If you return a regular value, it will be passed, as is, to the next handler.

    getJSON("/posts.json").then(function(json) {
      return json.post;
    }).then(function(post) {
      // proceed
    });

    The really awesome part comes when you return a promise from the first handler:

    getJSON("/post/1.json").then(function(post) {
      // save off post
      return getJSON(post.commentURL);
    }).then(function(comments) {
      // proceed with access to post and comments
    });

    转自: https://github.com/tildeio/rsvp.js

  • 相关阅读:
    vue项目中使用axios上传图片等文件
    es6入门set和map
    自定义组件实现双向数据绑定
    vue watch详细用法
    bind,call,applay的区别
    前端路由两种模式:hash、history
    jsonp封装成promise
    正则元字符理解2
    webpack配置
    vuex的几个细节
  • 原文地址:https://www.cnblogs.com/xjinza/p/4702637.html
Copyright © 2011-2022 走看看