ES6中的Promise

Promise 是一种异步编程解决方案,Promise是一个容器,保存着将来才会执行的代码;从语法角度来说Promise是一个对象,可以用来获取异步操作的消息。异步操作,同步解决,避免了层层嵌套的回调函数,可以链式调用降低了操作难度

Promise构造函数接收一个函数作为参数,也就是回调函数;该函数的两个参数分别是resolve和reject。resolve作为成功的回调函数,reject作为失败的回调函数。Promise对象代表一个异步操作有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。最后返回resolved(已定型)结果。

复制代码
 let p1=new Promise((resolve,reject)=>{
            if(3>2){
                resolve('success')
            }else{
                reject('error')
            }
        })
        p1.then((res)=>{
            console.log(res,'成功回调')
        }).catch((error)=>{
            console.log(error,'失败回调')
        }).finally(()=>{
            console.log('最终执行')
        })
		p1.then((res)=>{
            console.log(res,'成功')
        },(err)=>{
            console.log(res,'失败')
        });

静态方法 只能由构造函数本身去调用

定义在Promise中的方法,通过Promise可以直接调用

Promise.all(p1,p2)

参数:数组,数组中的元素为Promise实例

返回值:Promise实例,当p1,p2状态都为fulfilled时候,该实例的状态才为fulfilled,此时p1,p2的返回值组成一个数组,传递给该实例的回调函数;只要p1,p2的返回值有一个变为rejected,该实例状态为rejected;

Promise.race(p1,p2) 赛跑返回先请求成功的实例

参数:数组,数组中的元素为Promise实例 返回值:Promise实例,当p1,p2之中有一个实例率先改变状态,该实例的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给该实例的回调函数。

Promise.any(p1,p2) 参数:数组,数组中的元素为Promise实例 返回值:Promise实例,只要p1,p2状态有一个变为fulfilled,该实例的状态为fulfilled;p1,p2状态都变为rejected,该实例状态才为rejected

复制代码
function promise(url) {
			return new Promise((resolve, reject) => {
				let xhr = new XMLHttpRequest();
				xhr.open('get', url);
				xhr.send();
				xhr.onreadystatechange = function () {
					if (xhr.readyState === 4) {
						if (xhr.status === 200) {
							resolve(xhr.responseText)
						} else {
							reject(xhr.responseText)
						}
					}
				}
			})
		}
    let p1=getPromise('http://121.199.0.35:8888/index/article/findCategoryArticles');
    let p2=getPromise('http://121.199.0.35:8888/index/carousel/findAll');
    let p=Promise.any([p1,p2]);
    p.then((res)=>{
        console.log(res)
    }).catch((err)=>{
        console.log(err)
    })

setTimeout(function () {
  console.log('1');
})
new Promise(function (resolve) {
  console.log('2');
  resolve();
}).then(function () {
  console.log('3');
})
console.log('4');


async function async1() {
  console.log(1);
  const result = await async2();
  console.log(3);
}
async function async2() {
  console.log(2);
}
Promise.resolve().then(() => {
  console.log(4);
});
setTimeout(() => {
  console.log(5);
});
async1();
console.log(6);
相关推荐
阿猫的故乡23 分钟前
Vue过渡动画从入门到装X:淡入淡出、滑动、列表动画、第三方库全搞定
前端·javascript·vue.js
IManiy38 分钟前
总结之Vibe Coding前端骨架
前端
小和尚敲木头43 分钟前
vue3 vite动态拼接图片路径
javascript
JS菌1 小时前
AI Agent 沙箱双层防护体系:从权限过滤到内核隔离的完整实现
前端·人工智能·后端
Aphasia3111 小时前
从输入URL到页面展示全流程
前端·面试
我叫黑大帅1 小时前
前端如何竖屏固定视口背景
前端·javascript·面试
abcy0712131 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas
不会敲代码12 小时前
我花了三天时间,终于把 Cookie、XSS、CSRF 和浏览器存储给整明白了
javascript·面试
IT_陈寒2 小时前
Vite这个坑我帮你踩了,动态导入居然这样才生效
前端·人工智能·后端
贩卖黄昏的熊2 小时前
flex 布局快速梳理
开发语言·javascript·css3·html5