ajax函数返回Promise对象

2018-04-25 00:36:00
admin
原创
314
<!doctype html>
<html> 
<body> 
<script >
// 测试Promise对象:
function test(resolve, reject) {
	var timeOut = Math.random() * 2;
    console.log('set timeout to: ' + timeOut + ' seconds.');
    setTimeout(function () {
        if (timeOut < 1) {
            console.log('call resolve()...');
            resolve('200 OK');
        }
        else {
            console.log('call reject()...');
            reject('timeout in ' + timeOut + ' seconds.');
        }
    }, 1000);
}

//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);
                }
            }
        };
		var fd = new FormData();
        fd.append("a", "getUserInfo");
		request.open("POST" ,"http://www.ybao.org/api/has_cors.php" , true);
        request.send(fd);
    });
}
//测试定时器 Promise
function f(){
var p1 = new Promise(test);
var p2 = p1.then(function (result) {
    console.log('成功:' + result);
});
var p3 = p2.catch(function (reason) {
    console.log('失败:' + reason);
});
/*	
new Promise(test).then(function (result) {
    console.log('成功:' + result);
}).catch(function (reason) {
    console.log('失败:' + reason);
});
*/
}
//测试AJAX Promise
function f2(){
	var ajaxPromise = ajax("POST", "http://www.ybao.org/api/has_cors.php", "a=getUserInfo");
	ajaxPromise.then(function (result) {
    console.log('成功:' + result);
}).catch(function (reason) {
    console.log('失败:' + reason);
});
}
</script>
	<button type="button" onclick="f()" >测试定时器 Promise</button>
	<button type="button" onclick="f2()" >测试AJAX Promise</button>
</body> 
</html>				
				
文章分类
联系我们
电话: 18902328227
Email: 2689701946@qq.com
QQ: 2689701946
微信: 18902328227
地址: 广州番禺区繁华路
  • 在线客服
  • 关注微信
  • 联系电话
    • 欢迎咨询
    • 欢迎加入QQ群 303257430
  • 公众号:源宝网络
    • 联系电话及微信号 18902328227