(JS basis) Promise objects

Outline

PromiseThe object is a proxy object (a proxy value), the value of the proxied Promiseobject creation may be unknown .

PromiseObject has three states : pending(initial state), fulfilled(success status), rejected(failed state).

PromiseOnce the state of the object pendingbecomes fulfilledor rejectedwill not be changed .

PromiseState of the object changes fulfilledafter, through then()a callback function method; state to the rejectedrear, through the catch()callback function method.

In the introduction of the ES2018 finally(), it indicates that the Promiseexecution after the end (either " then" or " catch" led to the end) will perform incoming finallycallback method, the callback function has no parameters.


A simple example

create

By newcreate operator Promiseinstance, the only parameter with resolveand the rejecttwo parameters of executorthe function . resolveAnd rejectwhen the function is called, respectively, to Promisechange the status fulfilled(completion) or rejected(failure), a function accepts two parameters, as the information transfer success (or failure) to the processing method (corresponding to thenor catch).

let p = new Promise((resolve, reject) => {
  setTimeout(() => {
    if (Math.random() > 0.5) {
      resolve('resolve');
    } else {
      reject('reject');
    }
  }, 1000);
});复制代码

In the above example, one second after the random Promisestate of the object to fulfilled(completion) or rejected(failure).

deal with

Being created Promiseobjects will be executed immediately executorfunction, if we need to do something after the end of the asynchronous function, you need to call Promiseobjects then(), catch()and finally()methods. (Three methods will return a new Promisetarget, it is possible to use the " chaining ")

Connect examples:

p.then(res => {
  console.log(res);   // 'resolve'
}).catch(err => {
  console.log(err);   // 'reject'
}).finally(()=>{
  console.log('finally');    // 必定执行
});复制代码

As can be seen, then()and catch()the method is passed a callback, the callback function with a single parameter, corresponding to resolveand rejecta function of parameters passed. finally()Also passed a swap function, except that the callback function has no parameters.

Several scenes

Scenario 1: Multiple Promiseneeded in order to perform . ( Promise.prototype.then()You can pass another Promise objects )

const promise1 = new Promise(...);
const promise2 = new Promise(...);
const promise3 = new Promise(...);
// promise1成功执行后再执行promise2,再是promise3
promise1.then(promise2).then(promise3);复制代码

Scenario 2: Multiple Promiseneeds are successful . (Static Promise.all()method: )

const promise1 = new Promise(...);
const promise2 = new Promise(...);
const promise3 = new Promise(...);
// promise1/2/3 均成功后再执行 then ( 其中一个失败也不会执行 then )
Promise.all([promise1, promise2, promise3]).then(callback(){...});复制代码

Scenario 3: Multiple Promiserequires only one success . (Static Promise.race()method: )

const promise1 = new Promise(...);
const promise2 = new Promise(...);
const promise3 = new Promise(...);
// promise1/2/3 任意一个成功后执行 then
Promise.race([promise1, promise2, promise3]).then(callback(){...})
复制代码

Promise.resolve()

Promise.resolve()For generating a status fulfilledof Promisean object. Its parameters and .prototype.resolve()the same.

let p1 = Promise.resolve('resolve');
// 等效如下代码
let p2 = new Promise((resolve, reject) => {
  resolve('resolve');
});复制代码

Promise.reject()

Promise.reject()For generating a status rejectedof Promisean object. Its parameters and .prototype.reject()the same.

let p1 = Promise.reject('resolve');
// 等效如下代码
let p2 = new Promise((resolve, reject) => {
  reject('resolve');
});复制代码


Continue in-depth understanding of

the then () of the second parameter

In fact, the above description, there is no mention then()of the second argument, and its role as catch()a consistent method. See the following example:

let p = new Promise((resolve, reject) => {
  reject('reject');
})
p.then(res => { }, err => {
  console.log(err);     // 'reject'
});
p.catch(err => {
  console.log(err);     // 'reject'
});
复制代码

Parameter passing is not then () / catch () / finally ()

When then()/ catch()/ finally()not pass parameters, it will return to the original Promiseobjects of the same (but not equal) new Promiseobjects . Look at the following example:

// 不传参的"then"
let p1 = Promise.resolve('resolve');
let p2 = p1.then();
p2.then(res => {
  console.log(res);       // 'resolve'
});
console.log(p1 === p2);   // false
// 不传参的"catch"
let p3 = Promise.reject('reject');
let p4 = p3.catch();
p4.catch(res => {
  console.log(res);       // 'reject'
});
console.log(p3 === p4);   // false
// 不传参的"finally"
let p5 = Promise.resolve('resolve');
let p6 = p5.finally();
p6.then(res => {
  console.log(res);       // 'resolve'
});
console.log(p5 === p6);   // false
复制代码

Parameter then () / catch () / finally () is the return value of the callback function

When then()or catch()parameter values are returned 回调函数A, then()or catch()may return a status fulfilledof Promisethe object . New Promiseobject then()parameter callback method is 回调函数Athe return value.

Note that the state rejectof Promisethe object in then()the first function returns a swap will lead to error.

Note that finally()the swap function " return" and will not affect a new Promiseobject then()or catch()parameter values callback method.

If you think a bit about the text description, see the following example:

// 'resolve'状态被处理后的'return'
Promise.resolve('resolve').then(() => {
  return 'return1'
}).then(res => {
  console.log(res)
});   // 'return1'
// 'reject'状态被处理后的'return'
Promise.reject('resolve').catch(() => {
  return 'return2'
}).catch(err => {
  console.log('catch:', err)
}).then(res => {
  console.log('then:', res)
});   // 'then: return2'
// 'finally'的'return'只会返回与原promise相同的对象
Promise.resolve('resolve').finally(() => {
  return 'return3'
}).then(res => {
  console.log(res)
});   // 'resolve'
// 'reject'状态未被处理的'return'
Promise.reject('reject').then(() => {
  return 'return4'
}).then(res => {
  console.log(res);
});   // 报错!!复制代码

.resolve () parameters

resolve()(Including Promise.reject()and Promise.prototype.reject()) in addition to the use described above, but also the incomingthenable (i.e., objects with then the method), and returns the Promisefinal state of the object by the thenexecution decision method.

Note that thenablethe then()method is only passed a single callback function will be executed, the other parameters are ignored.

Look at the following example:

let thenable = {
  then(cb1, cb2) {
    cb1('cb1');
    cb2('cb2');
  }
}
// Promise.resolve()
Promise.resolve(thenable).then(
  res1 => {
    console.log(res1);  // 'cb1'
  },
  res2 => {
    console.log(res2);  // 不会执行
  }
).catch(err => {
  console.log(err);     // 不会执行
});
// Promise.prototype.resolve()
new Promise((resolve, reject) => {
  resolve(thenable);
}).then(res => {
  console.log(res);     // 'cb1'
});复制代码



Reproduced in: https: //juejin.im/post/5cf096d0e51d4577790c1c34

Guess you like

Origin blog.csdn.net/weixin_34060299/article/details/91454169