var p = new Promise( function( resolve , reject ){ setTimeout( function(){ // resolve(); // reject(); reject("hello 状态改变为失败"); }, 3000 ); });
console.log(p);
p.then(function( res ){ // 如果状态成功了,那么会执行当前的函数; console.log("状态改变为 resolved" , res); }) p.catch( function( res ){ console.log("状态改变为 rejected" , res); })
注意: Promise的状态只可以改变一次
封装简单的Ajax (Promise的作用是去掉回调函数的)
promise 是啥 ?
promise就是一个对象;在 ajax 封装里面返回 一个promise对象,在这个对象外面去监听状态的改变。
function ajaxPromise( url ){ var xhr = new XMLHttpRequest(); xhr.open("GET",url,true); xhr.send(); var p = new Promise( function( resolve ){ xhr.onload = function(){ resolve(xhr.responseText); } }) return p; } var p1 = ajaxPromise( "./04_CORS.php" ); var p2 = p1.then( function( res ){ console.log(res,"p1"); }) var p3 = p2.then( function(res){ console.log(res,"p2") var p3 = ajaxPromise( "./04_CORS.php" ); return p3; }) p3.then(function(res){ console.log(res,"p3"); })
var data = { a : 1, b : 2 } var p1 = fetch("./10_data.php",{ method: ‘POST‘, body: "a=1&b=2", headers: new Headers({ ‘Content-Type‘: ‘application/x-www-form-urlencoded‘ }) }); var p2 = p1.then( function( res ){ return res.json(); }) p2.then( function(res){ console.log(res); }) console.log(p1);
原文:https://www.cnblogs.com/SeventhMeteor/p/14753037.html