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);
相关推荐
子兮曰4 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰4 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万4 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝4 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋4 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁4 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄4 天前
JavaScript 隐式全局变量解析
javascript
汉堡大王95274 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大4 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师4 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端