web前端全系列 教程
1839个小节阅读:2243.8k
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
Promise 实例具有then
方法,也就是说,then
方法是定义在原型对象Promise.prototype
上的。它的作用是为 Promise 实例添加状态改变时的回调函数
then
方法返回的是一个新的Promise
实例。因此可以采用链式写法,即then
方法后面再调用另一个then
方法
xxxxxxxxxx
getJSON("/posts.json").then(function(json) {
return json.post;
}).then(function(post) {
// ...
},function (err){
console.log("rejected: ", err);
});
catch()
方法是.then(null, rejection)
或.then(undefined, rejection)
的别名,用于指定发生错误时的回调函数
xxxxxxxxxx
getJSON("http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php").then(
data =>{
console.log(data)
throw new Error('test');
},
error =>{
console.log("error"+error);
}
).catch(err =>{
console.log("catch"+err);
})
finally()
方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。该方法是 ES2018 引入标准的
xxxxxxxxxx
getJSON("http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php").then(
data =>{
console.log(data)
},
error =>{
console.log("error"+error);
}
).catch(err =>{
console.log("catch"+err);
}).finally(() =>{
console.log("成功失败都会执行");
})
Promise.all()
方法用于将多个 Promise 实例,包装成一个新的 Promise 实例
优点就是多个promise都有结果,才会触发then
或者catch
xxxxxxxxxx
var url1 = "http://iwenwiki.com/api/musicimg/1.png"
var url2 = "http://iwenwiki.com/api/musicimg/2.png"
var promise1 = new Promise(function (resolve, reject) {
var image = new Image();
image.src = url1;
image.onload = function () {
resolve(image)
}
image.onerror = function () {
reject(new Error('Could not load image at ' + url1))
}
})
var promise2 = new Promise(function (resolve, reject) {
var image = new Image();
image.src = url2;
image.onload = function () {
resolve(image)
}
image.onerror = function () {
reject(new Error('Could not load image at ' + url2))
}
})
Promise.all([promise1,promise2]).then(data =>{
console.log(data);
}).catch(error =>{
console.log(error);
})
实时效果反馈
1. 下列那个方法可以不管成功失败都会触发:
A then
B catch
C finally
D all
答案
1=>C