好程序员web前端教程分享怎么用promise解决回调和异步
2021-05-13 16:32
then() 成功后执行; 如果有两个参数:第一个参数成功后执行,第二个参数失败后执行;
catch() 失败后执行;
人promise all([]).then() 都成功后执行图then的第一个方法;
promise.race[(p1,p2,p3,---)] 只要有一个率先改变状态,promise就会执行对应的状态var promise = new Promise(function (resolved, rejected) { resolved(‘ok‘); rejected(‘no‘); //如果成功和失败同时写,执行先写的;(特点状态一旦改变,就不可逆了) }); promise.then(function(msg) { console.log(‘ok:‘ + msg); },function (msg) { console.log(‘no:‘ + msg); });
打印结果是: ok: ok
现在我们做一个练习: 使用promise 加载一张图片;加载成功就将图片加载到body中,如果加载失败,提示失败;var promise = new Promise(function (resolved, rejected) { var img = document.createElement(‘img‘); img.src = ‘./img/1.png‘; img.onload = function () { resolved(img) //如果加载成功就返回resolved() } img.onerror = function () { rejected(‘失败‘) //如果加载成功就返回rejected() } }) promise.then(function (msg) { document.body.appendChild(msg) },function (msg) { alert(msg) })
怎么样大家是不是对promise有了了解?
那么怎么用promise解决异步的问题呢?我们还是每隔1秒后做一次输出;
```function fn() {
var promise = new Promise(function(resolved, rejected) {
setTimeout(function() {
console.log(‘每隔一秒‘);
resolved()
}, 1000)
});
return promise;
}
fn().then(function() {
console.log(‘第一次输出‘);
return fn()
}).then(function() {
console.log(‘第二次输出‘);
return fn()
}).then(function () {
console.log(‘第三次输出‘);
})那Promise如何解决ajax回调的问题呢?咱们继续往下看.
function ajaxPromise(url) {
var promise = new Promise(function(resolved, rejected) {
var xhr = new XMLHttpRequest();
xhr.open(‘get‘, url);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
resolved( xhr.responseText); //告诉promise成功了
}
}
setTimeout(function () {//5秒后请求不到
rejected(‘error‘) //告诉promise失败了
},5000)
})
return promise;
}
document.onclick = function () {
var pro = ajaxPromise(‘data.json‘);
pro.then(function (msg) {
alert(msg) //如果路径对了,我们得到了数据
},function (msg) {
alert(msg) //如果路径错了我们弹出error
})
}
文章标题:好程序员web前端教程分享怎么用promise解决回调和异步
文章链接:http://soscw.com/index.php/essay/85216.html