仿制网站f3322免费域名申请
news/
2025/10/7 6:39:23/
文章来源:
仿制网站,f3322免费域名申请,线上推广方法,做网站推广利润文章目录 一、介绍状态特点流程 二、用法实例方法then()catchfinally() 构造函数方法all()race()allSettled()resolve()reject() 三、使用场景# 参考文献 一、介绍
Promise#xff0c;译为承诺#xff0c;是异步编程的一种解决方案#xff0c;比传统的解决方案#xff08;… 文章目录 一、介绍状态特点流程 二、用法实例方法then()catchfinally() 构造函数方法all()race()allSettled()resolve()reject() 三、使用场景# 参考文献 一、介绍
Promise译为承诺是异步编程的一种解决方案比传统的解决方案回调函数更加合理和更加强大
在以往我们如果处理多层异步操作我们往往会像下面那样编写我们的代码
doSomething(function(result) {doSomethingElse(result, function(newResult) {doThirdThing(newResult, function(finalResult) {console.log(得到最终结果: finalResult);}, failureCallback);}, failureCallback);
}, failureCallback);阅读上面代码是不是很难受上述形成了经典的回调地狱
现在通过Promise的改写上面的代码
doSomething().then(function(result) {return doSomethingElse(result);
})
.then(function(newResult) {return doThirdThing(newResult);
})
.then(function(finalResult) {console.log(得到最终结果: finalResult);
})
.catch(failureCallback);瞬间感受到promise解决异步操作的优点
链式操作减低了编码难度代码可读性明显增强
下面我们正式来认识promise
状态
promise对象仅有三种状态
pending进行中fulfilled已成功rejected已失败
特点
对象的状态不受外界影响只有异步操作的结果可以决定当前是哪一种状态一旦状态改变从pending变为fulfilled和从pending变为rejected就不会再变任何时候都可以得到这个结果
流程
认真阅读下图我们能够轻松了解promise整个流程 二、用法
Promise对象是一个构造函数用来生成Promise实例
const promise new Promise(function(resolve, reject) {});Promise构造函数接受一个函数作为参数该函数的两个参数分别是resolve和reject
resolve函数的作用是将Promise对象的状态从“未完成”变为“成功”reject函数的作用是将Promise对象的状态从“未完成”变为“失败”
实例方法
Promise构建出来的实例存在以下方法
then()catch()finally()
then()
then是实例状态发生改变时的回调函数第一个参数是resolved状态的回调函数第二个参数是rejected状态的回调函数
then方法返回的是一个新的Promise实例也就是promise能链式书写的原因
getJSON(/posts.json).then(function(json) {return json.post;
}).then(function(post) {// ...
});catch
catch()方法是.then(null, rejection)或.then(undefined, rejection)的别名用于指定发生错误时的回调函数
getJSON(/posts.json).then(function(posts) {// ...
}).catch(function(error) {// 处理 getJSON 和 前一个回调函数运行时发生的错误console.log(发生错误, error);
});Promise对象的错误具有“冒泡”性质会一直向后传递直到被捕获为止
getJSON(/post/1.json).then(function(post) {return getJSON(post.commentURL);
}).then(function(comments) {// some code
}).catch(function(error) {// 处理前面三个Promise产生的错误
});一般来说使用catch方法代替then()第二个参数
Promise对象抛出的错误不会传递到外层代码即不会有任何反应
const someAsyncThing function() {return new Promise(function(resolve, reject) {// 下面一行会报错因为x没有声明resolve(x 2);});
};浏览器运行到这一行会打印出错误提示ReferenceError: x is not defined但是不会退出进程
catch()方法之中还能再抛出错误通过后面catch方法捕获到
finally()
finally()方法用于指定不管 Promise 对象最后状态如何都会执行的操作
promise
.then(result {···})
.catch(error {···})
.finally(() {···});构造函数方法
Promise构造函数存在以下方法
all()race()allSettled()resolve()reject()try()
all()
Promise.all()方法用于将多个 Promise实例包装成一个新的 Promise实例
const p Promise.all([p1, p2, p3]);接受一个数组迭代对象作为参数数组成员都应为Promise实例
实例p的状态由p1、p2、p3决定分为两种
只有p1、p2、p3的状态都变成fulfilledp的状态才会变成fulfilled此时p1、p2、p3的返回值组成一个数组传递给p的回调函数只要p1、p2、p3之中有一个被rejectedp的状态就变成rejected此时第一个被reject的实例的返回值会传递给p的回调函数
注意如果作为参数的 Promise 实例自己定义了catch方法那么它一旦被rejected并不会触发Promise.all()的catch方法
const p1 new Promise((resolve, reject) {resolve(hello);
})
.then(result result)
.catch(e e);const p2 new Promise((resolve, reject) {throw new Error(报错了);
})
.then(result result)
.catch(e e);Promise.all([p1, p2])
.then(result console.log(result))
.catch(e console.log(e));
// [hello, Error: 报错了]如果p2没有自己的catch方法就会调用Promise.all()的catch方法
const p1 new Promise((resolve, reject) {resolve(hello);
})
.then(result result);const p2 new Promise((resolve, reject) {throw new Error(报错了);
})
.then(result result);Promise.all([p1, p2])
.then(result console.log(result))
.catch(e console.log(e));
// Error: 报错了race()
Promise.race()方法同样是将多个 Promise 实例包装成一个新的 Promise 实例
const p Promise.race([p1, p2, p3]);只要p1、p2、p3之中有一个实例率先改变状态p的状态就跟着改变
率先改变的 Promise 实例的返回值则传递给p的回调函数
const p Promise.race([fetch(/resource-that-may-take-a-while),new Promise(function (resolve, reject) {setTimeout(() reject(new Error(request timeout)), 5000)})
]);p
.then(console.log)
.catch(console.error);allSettled()
Promise.allSettled()方法接受一组 Promise 实例作为参数包装成一个新的 Promise 实例
只有等到所有这些参数实例都返回结果不管是fulfilled还是rejected包装实例才会结束
const promises [fetch(/api-1),fetch(/api-2),fetch(/api-3),
];await Promise.allSettled(promises);
removeLoadingIndicator();resolve()
将现有对象转为 Promise对象
Promise.resolve(foo)
// 等价于
new Promise(resolve resolve(foo))参数可以分成四种情况分别如下
参数是一个 Promise 实例promise.resolve将不做任何修改、原封不动地返回这个实例参数是一个thenable对象promise.resolve会将这个对象转为 Promise对象然后就立即执行thenable对象的then()方法参数不是具有then()方法的对象或根本就不是对象Promise.resolve()会返回一个新的 Promise 对象状态为resolved没有参数时直接返回一个resolved状态的 Promise 对象
reject()
Promise.reject(reason)方法也会返回一个新的 Promise 实例该实例的状态为rejected
const p Promise.reject(出错了);
// 等同于
const p new Promise((resolve, reject) reject(出错了))p.then(null, function (s) {console.log(s)
});
// 出错了Promise.reject()方法的参数会原封不动地变成后续方法的参数
Promise.reject(出错了)
.catch(e {console.log(e 出错了)
})
// true三、使用场景
将图片的加载写成一个Promise一旦加载完成Promise的状态就发生变化
const preloadImage function (path) {return new Promise(function (resolve, reject) {const image new Image();image.onload resolve;image.onerror reject;image.src path;});
};通过链式操作将多个渲染数据分别给个then让其各司其职。或当下个异步请求依赖上个请求结果的时候我们也能够通过链式操作友好解决问题
// 各司其职
getInfo().then(res{let { bannerList } res//渲染轮播图console.log(bannerList)return res
}).then(res{let { storeList } res//渲染店铺列表console.log(storeList)return res
}).then(res{let { categoryList } resconsole.log(categoryList)//渲染分类列表return res
})通过all()实现多个请求合并在一起汇总所有请求结果只需设置一个loading即可
function initLoad(){// loading.show() //加载loadingPromise.all([getBannerList(),getStoreList(),getCategoryList()]).then(res{console.log(res)loading.hide() //关闭loading}).catch(err{console.log(err)loading.hide()//关闭loading})
}
//数据初始化
initLoad()通过race可以设置图片请求超时
//请求某个图片资源
function requestImg(){var p new Promise(function(resolve, reject){var img new Image();img.onload function(){resolve(img);}//img.src https://b-gold-cdn.xitu.io/v3/static/img/logo.a7995ad.svg; 正确的img.src https://b-gold-cdn.xitu.io/v3/static/img/logo.a7995ad.svg1;});return p;
}//延时函数用于给请求计时
function timeout(){var p new Promise(function(resolve, reject){setTimeout(function(){reject(图片请求超时);}, 5000);});return p;
}Promise
.race([requestImg(), timeout()])
.then(function(results){console.log(results);
})
.catch(function(reason){console.log(reason);
});# 参考文献
https://es6.ruanyifeng.com/#docs/promise
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/930016.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!