promise学习

来源:互联网 发布:淘宝互刷平台排行榜 编辑:程序博客网 时间:2024/05/22 00:29

1.将传统的ajax调用改写为promise的方式

function get(url) {  // Return a new promise.  return new Promise(function(resolve, reject) {    // Do the usual XHR stuff    var req = new XMLHttpRequest();    req.open('GET', url);    req.onload = function() {      // This is called even on 404 etc      // so check the status      if (req.status == 200) {        // Resolve the promise with the response text        resolve(req.response);      }      else {        // Otherwise reject with the status text        // which will hopefully be a meaningful error        reject(Error(req.statusText));      }    };    // Handle network errors    req.onerror = function() {      reject(Error("Network Error"));    };    // Make the request    req.send();  });}
get('story.json').then(function(response) {  console.log("Success!", response);}, function(error) {  console.error("Failed!", error);})
2.当从 then() 回调中返回某些内容时,如果返回一个值,则会以该值调用下一个 then()。但是,如果返回类promise 的内容,下一个then() 则会等待,并仅在 promise 产生结果(成功/失败)时调用。


原创粉丝点击