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);

你可能感兴趣的:(es6,前端,javascript)