1、案例
var p = new Promise(function(resolve,reject){
//做一下操作
setTimeout(function(){
console.log('執行完畢');
resolve('執行成的隨便數據')
},2000)
})
//在上面的代碼中,我們執行了一個異步操作,也就是setTimeout,2秒後,輸出“執行完成”,並且調用resolve方法
var p1 = new Promise(function(resolve,reject){
resolve(1);
})
p1.then(function(value){
//成功回調函數
alert('success: '+value)
},function(error){
//失敗回調函數
alert('fail')
})
2、案例
<script type="text/javascript">
function ajax(url,succ,fail){
var xhr = new XMLHttpRequest();
xhr.open('GET',url,true);
xhr.onreadystatechange=function(){
if(xhr.readyState == 4 && xhr.status == 200){
succ.call(this,xhr.responseText);
}
}
xhr.send();
}
window.onload=function(){
var oBtn = document.getElementById('btn1');
var oBox = document.getElementById('box1');
oBtn.onclick=function(){
ajax('a.txt',function(str){
alert('ok'+str);
},function(){
alert('no')
})
}
}
</script>
<input type="button" value="獲取" id="btn1" />
<div id="box1"></div>
3、案例
<script type="text/javascript">
function ajax(url,succ,fail){
var xhr = new XMLHttpRequest();
xhr.open('GET',url,true);
xhr.onreadystatechange=function(){
if(xhr.readyState == 4 && xhr.status == 200){
succ.call(this,xhr.responseText);
}
}
xhr.send();
}
window.onload=function(){
var oBtn = document.getElementById('btn1');
var oBox = document.getElementById('box1');
oBtn.onclick=function(){
ajax('a.txt',function(str){
alert('ok'+str);
},function(){
alert('no')
})
}
}
</script>
<input type="button" value="獲取" id="btn1" />
<div id="box1"></div>
4、案例
<script type="text/javascript">
function ajax(url,succ,fail){
var xhr = new XMLHttpRequest();
xhr.open('GET',url,true);
xhr.onreadystatechange=function(){
if(xhr.readyState == 4 && xhr.status == 200){
succ.call(this,xhr.responseText);
}
}
xhr.send();
}
window.onload=function(){
var oBtn = document.getElementById('btn1');
var oBox = document.getElementById('box1');
oBtn.onclick=function(){
var p1 = new Promise(function(resolve,reject){
ajax('a.txt',function(str){
resolve(str);
},function(err){
reject(err);
})
})
p1.then(function(str){
oBox.innerHTML = str;
},function(err){
oBox.innerHTML = err;
})
}
}
</script>
<input type="button" value="獲取" id="btn1" />
<div id="box1"></div>
catch 用來捕獲報錯
//catch 用來捕獲報錯
var p1 = new Promise(function(resolve,reject){
resolve('成功了')
})
p1.then(function(value){
console.log(value);
throw '報錯了';
},function(err){
console.log(err)
}).catch(function(e){
console.log(e); //報錯了
})