目录

 1、promise是同步还是异步?

2、Promise的特点

3、Promise用法

4、实例方法

5、构造函数方法

 6、使用场景

7、参考文献

8、宏任务,微任务

从语法上说,Promise 是一个对象,从它可以获取异步操作的消息。Promise 提供统一的 API,各种异步操作都可以用同样的方法进行处理。

 1、promise是同步还是异步?

 1、Promise 是用来管理异步编程的,它本身不是异步的 ,promise是同步代码

 2、promise的回调then,catch是异步 

 Promise 是用来管理异步编程的,它本身不是异步的 ,promise是同步代码

let promise = new Promise((resolve, reject) => {

console.log(1);

})

console.log(2);

console.log(promise);

// 1

// 2

// Promise {}

promise的回调then,catch是异步 :Promise 新建后立即执行,所以首先输出的是1,其次2。然后,then方法指定的回调函数,将在当前脚本所有同步任务执行完才会执行,所以resolved最后输出。

let promise = new Promise((resolve, reject) => {

console.log(1);

resolve()

})

promise.then(function() {

console.log('resolved.');

});

console.log(2);

// 1 2 resolved

 

2、Promise的特点

(1)对象的状态不受外界影响

        Promise对象代表一个异步操作,有三种状态:

   pending(进行中)、fulfilled(已成功)和rejected(已失败)

        只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。这也是Promise这个名字的由来,它的英语意思就是“承诺”,表示其他手段无法改变

(2)一旦状态改变,就不会再变,任何时候都可以得到这个结果

        只有两种状态的可能:从pending变为fulfilled、从pending变为rejected

3、Promise用法

ES6 规定,Promise对象是一个构造函数,用来生成Promise实例。

// 下面代码创造了一个Promise实例

const promise = new Promise(function(resolve, reject) {

// ... some code

if (/* 异步操作成功 */){

resolve(value);

} else {

reject(error);

}

});

Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject。它们是两个函数,由 JavaScript 引擎提供,不用自己部署。

        1.  resolve函数的作用是,将Promise对象的状态从“未完成”变为“成功”(即从 pending 变为 resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;

        2.  reject函数的作用是,将Promise对象的状态从“未完成”变为“失败”(即从 pending 变为 rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。

4、实例方法

Promise构建出来的实例存在以下方法:

then()catch()finally()

then()

        

then是实例状态发生改变时的回调函数,第一个参数是resolved状态的回调函数,第二个参数是rejected状态的回调函数

then方法返回的是一个新的Promise实例,也就是promise能链式书写的原因

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(() => {···});

5、构造函数方法

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的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数只要p1、p2、p3之中有一个被rejected,p的状态就变成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);

 6、使用场景

1、将图片的加载写成一个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;

});

};

2、通过链式操作,将多个渲染数据分别给个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 } = res

console.log(categoryList)

//渲染分类列表

return res

})

3、通过all()实现多个请求合并在一起,汇总所有请求结果,只需设置一个loading即可

function initLoad(){

// loading.show() //加载loading

Promise.all([getBannerList(),getStoreList(),getCategoryList()]).then(res=>{

console.log(res)

loading.hide() //关闭loading

}).catch(err=>{

console.log(err)

loading.hide()//关闭loading

})

}

//数据初始化

initLoad()

4、通过race可以设置图片请求超时7、

//请求某个图片资源

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

});

7、参考文献

ES6 入门教程

8、宏任务,微任务

宏任务: 主线程代码, setTimeout 等属于宏任务, 上一个宏任务执行完, 才会考虑执行下一个宏任务

微任务: promise .then .catch 的需要执行的内容, 属于微任务, 满足条件的微任务, 会被添加到当前宏任务的最后去执行

console.log(1)

setTimeout(function () {

console.log(2) // 宏任务

}, 0)

const p = new Promise((resolve, reject) => {

resolve(1000)

})

p.then((data) => {

console.log(data) // 微任务

})

console.log(3)

// 1 3 1000 2

9、相较于Promise,async/await有何优势?

同步化代码的阅读体验(Promise 虽然摆脱了回调地狱,但 then 链式调⽤的阅读负担还是存在的)和同步代码更一致的错误处理方式( async/await 可以⽤成熟的 try/catch 做处理,比 Promise 的错误捕获更简洁直观)调试时的阅读性, 也相对更友好

好文推荐

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。