Home > Web Front-end > JS Tutorial > body text

What is Promise? Introduction to Promises

不言
Release: 2018-10-17 14:55:13
forward
3566 people have browsed it

The content of this article is about what is Promise? The introduction of Promise has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In fact, I have wanted to write about the use of Promise for a long time. One is that it is often used in the actual coding process, and the other is that sometimes friends will encounter some problems when using it.

Promise is indeed one of the API features in ES6 that has truly had the biggest impact on the way you write JS.
This article is a summary of the actual use process
Look at the file creation time 2017-10-09, procrastination is really terrible. . . We still need to strengthen our execution ability! Don’t forget your original intention, come on!

Preface && Basic Concepts

Promise is a solution to JS asynchronousness. Compared with traditional callback functions, Promise can solve the problem of serious nesting of multiple callbacks. .

The Promise object represents an asynchronous operation and has three states: pending, fulfilled or rejected. The state transition can only be pending -> fulfilled or pending -> rejected, and this process is irreversible once it occurs.

I personally think that explaining Promise actually needs to be divided into two parts

  1. For the Promise constructor Instructions for use.

  2. Promise Some methods on the prototype object.

Promise constructor

ES6 stipulates that the Promise object is a constructor used to generate Promise instances.

The Promise constructor accepts a function as a parameter. The two parameters of the function are resolve and reject. They are two functions provided by the JavaScript engine and do not need to be deployed by yourself.

The role of the resolve function is to change the state of the Promise object from "uncompleted" to "successful" (that is, from pending to fulfilled). It is called when the asynchronous operation is successful, and the result of the asynchronous operation is used as The parameters are passed out; the function of
reject function is to change the status of the Promise object from "uncompleted" to "failed" (that is, from pending to rejected), and is called when the asynchronous operation fails and reports the asynchronous operation. The error is passed as a parameter.

The following code creates a Promise instance.

function request() {
  return new Promise((resolve, reject) => {
    /* 异步操作成功 */
    setTimeout(() => {
      resolve("success");
    }, 1000);
    // 取消注释这里可以体现,Promise 的状态一旦变更就不会再变化的特性
    // reject('error');
  });
}
Copy after login

Receive

request()
  .then(result => {
    console.info(result);
  })
  .catch(error => {
    console.info(error);
  });
Copy after login

After the above new Promise(), in addition to using catch to capture errors, you can also use the then method to specify# The callback functions of ##resolve and reject can also achieve the purpose of catching errors.

request().then(
  result => {
    console.info(result);
  },
  error => {
    console.info(error);
  }
);
Copy after login
Methods on the prototype

Promise.prototype.then()

p.then(onFulfilled, onRejected)
Copy after login

Thethen method is a method defined on Promise.prototype, as in the above example, there are Two parameters, fulfilled callback function and rejected callback function, the second parameter is optional.

Two key points:

  1. The return value of the then method is a new

    Promise instance, so for the caller, get A Promise object still returns a Promise after calling then, and its behavior is related to the return value of the callback function in then. As follows:

  • If the callback function in then returns a value, then the Promise returned by then will become the accepted state, and the returned value will be regarded as the accepted state. The parameter value of the callback function.

  • If the callback function in then throws an error, then the Promise returned by then will become a rejected state, and the thrown error will be used as the parameter value of the callback function in the rejected state.

  • If the callback function in then returns a Promise that is already in the acceptance state, then the Promise returned by then will also become the acceptance state, and the parameters of the callback function of the acceptance state of that Promise will be The value is used as the parameter value of the accept state callback function of the returned Promise.

  • If the callback function in then returns a Promise that is already in a rejected state, then the Promise returned by then will also become a rejected state, and the parameters of the callback function of the rejected state of that Promise will be The value is used as the parameter value of the rejection status callback function of the returned Promise.

  • If the callback function in then returns a Promise with an undetermined state (pending), then the state of the Promise returned by then is also pending, and its final state is the same as that of that Promise. ;At the same time, the parameters of the callback function called when it becomes the final state are the same as the parameters of the callback function when the Promise becomes the final state.

  1. Chain call. Convert the code format of nested callbacks into a vertical mode of chained calls.

For example, callback form: an example of callback hell

a(a1 => {
  b(a1, b1 => {
    c(b1, c1 => {
      d(c1, d1 => {
        console.log(d1);
      });
    });
  });
});
Copy after login

Such horizontal expansion can be modified to (a, b, c, d) all return Promise The vertical structure of function

a()
  .then(b)
  .then(c)
  .then(d)
  .then(d1 => {
    console.log(d1);
  });
//===== 可能上面的例子并不太好看 ===下面这样更直观
a()
  .then(a1 => b(a1))
  .then(b1 => c(b1))
  .then(c1 => d(c1))
  .then(d1 => {
    console.log(d1);
  });
Copy after login

looks much cleaner.

Promise.prototype.catch()

In addition to then(), there is also the catch() method on the Promise.prototype prototype chain, which is the handler function for rejection situations.

其实 它的行为与调用 Promise.prototype.then(undefined, onRejected) 相同。 (事实上, calling obj.catch(onRejected) 内部 calls obj.then(undefined, onRejected)).

// 1.
request().then(
  result => {
    console.info(result);
  },
  error => {
    console.info(error);
  }
);

// 2.
request()
  .then(result => {
    console.info(result);
  })
  .catch(error => {
    console.info(error);
  });
Copy after login

如上这个例子:两种方式在使用,与结果基本上是等价的,但是 仍然推荐第二种写法,下面我会给出原因:

  1. 在 Promise 链中 Promise.prototype.then(undefined, onRejected),onRejected 方法无法捕获当前 Promise 抛出的错误,而后续的 .catch 可以捕获之前的错误。

  2. 代码冗余

new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("reject");
  }, 1000);
})
  .then(
    result => {
      console.log(result + "1");
      throw Error(result + "1"); // 抛出一个错误
    },
    error => {
      console.log(error + ":1"); // 不会走到这里
    }
  )
  .then(
    result => {
      console.log(result + "2");
      return Promise.resolve(result + "2");
    },
    error => {
      console.log(error + ":2");
    }
  );
// reject1, Error: reject1:2
Copy after login

如果使用 .catch 方法,代码会简化很多,这样实际上是延长了 Promise 链

new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("reject");
  }, 1000);
})
  .then(result => {
    console.log(result + "1");
    throw Error(result + "1"); // 抛出一个错误
  })
  .then(result => {
    console.log(result + "2");
    return Promise.resolve(result + "2");
  })
  .catch(err => {
    console.log(err);
  });
// reject1, Error: reject1:2
Copy after login

Promise.prototype.finally()

暂未完全成为标准的一部分,处于:Stage 4

finally() 方法返回一个 Promise,在执行 then() 和 catch() 后,都会执行finally指定的回调函数。(回调函数中无参数,仅仅代表 Promise 的已经结束

等同于使用 .then + .catch 延长了原有的 Promise 链的效果,避免同样的语句需要在 then() 和 catch() 中各写一次的情况。

mdn-Promise-finally

Promise 对象上的方法

Promise.all() 用来处理 Promise 的并发

Promise.all 会将多个 Promise 实例封装成一个新的 Promise 实例,新的 promise 的状态取决于多个 Promise 实例的状态,只有在全体 Promise 都为 fulfilled 的情况下,新的实例才会变成 fulfilled 状态。;如果参数中 Promise 有一个失败(rejected),此实例回调失败(rejecte),失败原因的是第一个失败 Promise 的结果。

举个例子:

Promise.all([
  new Promise(resolve => {
    setTimeout(resolve, 1000, "p1");
  }),
  new Promise(resolve => {
    setTimeout(resolve, 2000, "p2");
  }),
  new Promise(resolve => {
    setTimeout(resolve, 3000, "p3");
  })
])
  .then(result => {
    console.info("then", result);
  })
  .catch(error => {
    console.info("catch", error);
  });
// [p1,p2,p3]

Promise.all([
  new Promise(resolve => {
    setTimeout(resolve, 1000, "p1");
  }),
  new Promise(resolve => {
    setTimeout(resolve, 2000, "p2");
  }),
  Promise.reject("p3 error")
])
  .then(result => {
    console.info("then", result);
  })
  .catch(error => {
    console.info("catch", error);
  });
// p3 error
Copy after login

获取 cnode 社区的 精华贴的前十条内容

fetch("https://cnodejs.org/api/v1/topics?tab=good&limit=10")
  .then(res => res.json())
  .then(res => {
    const fetchList = res.data.map(item => {
      return fetch(`https://cnodejs.org/api/v1/topic/${item.id}`)
        .then(res => res.json())
        .then(res => res.data);
    });
    Promise.all(fetchList).then(list => {
      console.log(list);
    });
  });
Copy after login

Promise.race() 竞态执行

Promise.race 也会将多个 Promise 实例封装成一个新的Promise实例,只不过新的 Promise 的状态取决于最先改变状态的 Promise 实例的状态。

在前端最典型的一个用法是为 fetch api 模拟请求超时。

Promise.race([
  fetch("https://cnodejs.org/api/v1/topics?tab=good&limit=10").then(res =>
    res.json()
  ),
  new Promise((resolve, reject) => {
    setTimeout(reject, 1, "error");
  })
])
  .then(result => {
    console.info("then", result);
  })
  .catch(error => {
    console.info("catch", error); // 进入这里
  });
Copy after login

上述例子中只要请求 未在 1 毫秒内结束就会进入 .catch() 方法中,虽然不能将请求取消,但是超时模拟却成功了

Promise.resolve(value) && Promise.reject(reason)

这两个方法都能用来创建并返回一个新的 Promise , 区别是 Promise.resolve(value) 携带进新的 Promise 状态是 fulfilled。而 Promise.reject(reason) 带来的 rejected

有的时候可以用来简化一些创建 Promise 的操作如:

const sleep = (time = 0) => new Promise(resolve => setTimeout(resolve, time));
// 这里创建一个 睡眠,并且打印的链
Promise.resolve()
  .then(() => {
    console.log(1);
  })
  .then(() => sleep(1000))
  .then(() => {
    console.log(2);
  })
  .then(() => sleep(2000))
  .then(() => {
    console.log(3);
  });
Copy after login

有时也用来 手动改变 Promise 链中的返回状态 ,当然这样实际上和 直接返回一个值,或者是 使用 throw Error 来构造一个错误,并无区别。到底要怎么用 就看个人喜好了

new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("resolve"); // 1.
  }, 1000);
})
  .then(result => {
    return Promise.reject("reject1"); // 2.
  })
  .then(
    result => {
      return Promise.resolve(result + "2");
    },
    err => {
      return Promise.resolve(err); // 3.
    }
  )
  .then(res => {
    console.log(res); // 4.
  })
  .catch(err => {
    console.log(err + "err");
  });
// reject1
Copy after login

几个例子

下面来看几个例子:

关于执行顺序,具体可搜索,js 循环

new Promise((resolve, reject) => {
  console.log("step 1");
  resolve();
  console.log("step 2");
}).then(() => {
  console.log("step 3");
});
console.log("step 4");

// step 1, step 2, step 4 , step 3
Copy after login

在使用 Promise 构造函数构造 一个 Promise 时,回调函数中的内容就会立即执行,而 Promise.then 中的函数是异步执行的。

关于状态不可变更

let start;
const p = new Promise((resolve, reject) => {
  setTimeout(() => {
    start = Date.now();
    console.log("once");
    resolve("success");
  }, 1000);
});
p.then(res => {
  console.log(res, Date.now() - start);
});
p.then(res => {
  console.log(res, Date.now() - start);
});
p.then(res => {
  console.log(res, Date.now() - start);
});
Copy after login

Promise 构造函数只执行一次,内部状态一旦改变,有了一个值,后续不论调用多少次then()都只拿到那么一个结果。

关于好像状态可以变更

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("success");
  }, 1000);
});

const p2 = p1.then((resolve, reject) => {
  throw new Error("error");
});

console.log("p1", p1);
console.log("p2", p2);

setTimeout(() => {
  console.log("p1", p1);
  console.log("p2", p2);
}, 2000);
Copy after login

观察这一次的打印
第一次打印出两个 Promise 的时候都是 pending ,因为 p2 是基于 p1 的结果,p1 正在 pending ,立即打印出的时候肯定是 pending ;第二次打印的时候,因为 p1 的状态为 resolved ,p2 为 rejected ,这个并不是已经为 fulfilled 状态改变为 rejected ,而是 p2 是一个新的 Promise 实例,then() 返回新的 Promise 实例。

关于透传

Promise.resolve(11)
  .then(1)
  .then(2)
  .then(3)
  .then(res => {
    console.info("res", res);
  });
//   11
Copy after login

给 then 方法传递了一个非函数的值,等同于 then(null),会导致穿透的效果,就是直接过掉了这个 then() ,直到符合规范的 then() 为止。

Promise 的串行调用

使用 Array.reduce 方法串行执行 Promise

const sleep = (time = 0) => new Promise(resolve => setTimeout(resolve, time));
[1000, 2000, 3000, 4000].reduce((Promise, item, index) => {
  return Promise.then(res => {
    console.log(index + 1);
    return sleep(item);
  });
}, Promise.resolve());
// 在分别的等待时间后输出 1,2,3,4
Copy after login

这篇文章到这里就基本上结束了,相信 如果能理解上面的内容,并且在实际项目中使用的话。应该会让工作更高效吧,对于新的异步使用应该也会更加的得心应手。Promise 的使用相对简单,可能后续再出一篇如何实现一个 Promise 吧。

The above is the detailed content of What is Promise? Introduction to Promises. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template