本文的一些知识点摘自MDN web doc, 如果大家想深入研究,能够去看原文[应用Promise] & [Promise文档]

  • Promise有什么用?

在没有Promise之前,咱们在实现异步的时候通常通过回调函数,有时候因为业务逻辑简单,会呈现一个回调嵌套另一个回调,造成回调天堂。ES6 Promise的呈现提供了一种更好的解决异步的办法。

  • Promise如何应用

场景:工作Task分为A步骤和B步骤,A步骤胜利与否决定咱们执行B_success还是B_failure。

// 当咱们单纯的通过回调函数实现function function_A(params, callback_success, callback_failure) {    // What we need to do in A    if(success){        callback_success();    } else {        callback_failure();    }}function function_B_success() {    // What we need to do in B after A succeed}function function_B_failure() {    // What we need to do in B after A failed}// 执行Taskfunction_A(params, function_B_success, function_B_failure);

当初咱们有了Promise,他是一个对象,示意一个异步操作的后果是实现了还是失败了

// 第一种写法const promise = function_A(params); promise.then(function_B_success, function_B_failure);//第二种写法function_A(params).then(function_B_success, function_B_failure);
  • Promise约定的是什么?

Promise在英语里是约定,允诺的意思。Promise约定的有三点:

  1. 在本轮事件循环运行实现之前,回调函数是不会被调用的。
  2. 即便异步操作曾经实现(胜利或失败),在这之后通过then增加的回调函数也会被调用。
  3. 通过屡次调用then能够增加多个回调函数,它们会依照插入程序执行。
  • 什么是事件循环?

在JS中有一套并发模型,负责收集,解决队伍中的工作。这个解决模型就叫做事件循环。大家如果想深刻理解能够读MDN文档当前有机会独自和大家聊事件循环。

  • .then()办法

then()最多须要两个参数, Promise 的胜利和失败状况的回调函数。

p.then(onFulfilled\[, onRejected\]);p.then(value => {  // fulfillment}, reason => {  // rejection});

then会返回一个新的Promise对象, 如下

const promise1 = doSomething();const promise2 = promise1.then(successCallback, failureCallback);

所以then会返回一个新的promise对象,示意上一个promise回调函数的状态,也就是doSomething胜利或者失败后的回调函数的执行状态,这样就造成了一个链条。咱们称其为链式调用。
如果要实现链式调用,前一个promise要进行return,不能够简略的写成箭头函数。
链式调用中如果某一环抛出谬误throw new Error(‘error’);,则间接跳至catch,然而catch之后的then不会被影响。

  • Promise的三种状态 -- pending/fulfillment/rejection

Pending示意未决,即还在执行中,未失去后果
Fulfillment示意胜利
Rejectection示意失败

  • .resolve()办法

**Promise.resolve(value)**办法返回一个以给定值解析后的Promise对象。如果这个值是一个 promise ,那么将返回这个 promise ;如果这个值是thenable(即带有then办法),返回的promise会“追随”这个thenable的对象,采纳它的最终状态;否则返回的promise将以此值实现。此函数将类promise对象的多层嵌套展平。
以上是MDN给出的解释,简略来讲就是两种状况:

  1. value是一个简略的值,比方数字,字符串,数组,这个时候Promise.resolve(value)返回一个promise对象,这个对象的then的胜利回调函数参数为value。
  2. value是一个thenable对象
// original是咱们说的thenable对象var original = Promise.resolve(33);// promise是咱们通过resolve返回的Promise对象var promise = Promise.resolve(original);// 这时候的promise胜利状况会进行original这个thenable的最终后果,也就是一层一层走到最底层promise.then(function(value) {  console.log('value: ' + value);});console.log('original === promise ? ' + (original === promise));/**  打印程序如下,这里有一个同步异步先后执行的区别*  original === cast ? true*  value: 33*/
  • reject()办法

返回一個帶有拒絕起因的Promise对象。

//因为reject传入Error对象,所以resolved不会被调用function resolved(result) {  console.log('Resolved');}//rejected被调用function rejected(result) {  console.error(result);}//Error是一个谬误结构器Promise.reject(new Error('fail')).then(resolved, rejected);// expected output: Error: fail