首页 > 其他 > 详细

ES6——Promise

时间:2018-06-23 00:54:11      阅读:279      评论:0      收藏:0      [点我收藏+]

IMAGE加载

Callback Hell

function loadImg(src,callback,fail) {
var img = document.createElement(‘img‘);
img.onload = function() {
callback(img)
}
img.onerror = function() {
fail();
}
img.src=src;
}
var src = "....";
loadImg(src,function(img) {
console.log(img)
},function() {
console.log(‘load failed‘)
})

promise语法 

function loadImg(src) {
return new Promise(function(resolve,reject){
const img = document.createElement(‘img‘);
img.onload = function() {
resolve(img)
}
img.onerror = function() {
reject();
}
img.src=src;
})
}
const result =loadImg(src);
result.then(function(img){
console.log(img);
},function(){
console.log(‘load failed‘);
})

ajax函数将返回Promise对象

function ajax(method, url, data) {
    var request = new XMLHttpRequest();
    return new Promise(function (resolve, reject) {
        request.onreadystatechange = function () {
            if (request.readyState === 4) {
                if (request.status === 200) {
                    resolve(request.responseText);
                } else {
                    reject(request.status);
                }
            }
        };
    });
} 

Fetch函数返回Promose

import { notification } from ‘antd‘;
fetch(url, newOptions)
  .then(checkStatus) //checkStatus中主要是对response的status做判断
  .then((response) => { return response.json(); })
  .catch((error) => {
    if (error.code) {
      notification.error({
        message: error.name,
        description: error.message,
      });
    }
    if (‘stack‘ in error && ‘message‘ in error) {
      notification.error({
        message: `请求错误: ${url}`,
        description: error.message,
      });
    }
    return error;
  });

  

ES6——Promise

原文:https://www.cnblogs.com/fuGuy/p/9215884.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!