不废话,粘代码
function ajax(method, url, data) { let 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); } } }; request.open(method, url); request.send(data); }); } let p = ajax('GET', 'config.json'); p.then(function (text) { // 如果AJAX成功,获得响应内容 console.log(text); }).catch(function (status) { // 如果AJAX失败,获得响应代码 console.log(status); });
以上是模拟ajax实现
let promise=new Promise((resolve, reject) => { console.log("1") reject("我错了"); resolve("123"); }); promise.then(function(data){ console.log("3") console.log(data) },function(err){ console.log("4") console.log(err) }) console.log("2")
以上是用来测试promise的执行顺序