使用 ES6 / ES2015 在 JavaScript 中许诺

Promises 是 ES6 (ES2015) JavaScript 规格中的一个新功能,允许您很容易地处理非同步代码,而无需解决多层次的回调函数。

以下是我们如何声明一个基本的承诺。你通常会称之为非同步的东西,例如外部API。

 1let myPromise = new Promise((resolve, reject) => {
 2  let data;
 3  setTimeout(() => {
 4    data = "Some payload";
 5
 6if (data) {
 7  resolve(data);
 8} else {
 9  reject();
10}

注意一个新的承诺是如何启动的,有两个函数作为论点,一个函数是它的成功和一个函数是它的失败。

1myPromise.then(data => {
2  console.log('Received: ' + data);
3}).catch(() => {
4  console.log("There was an error");
5});

上面的将记录以下内容在控制台:

1Received: Some payload

如果没有收到数据,则会记录以下内容:

1There was an error

链接承诺

承诺还可以链接与多个然后函数一起,然后一个函数的返回值就会成为链接中的下一个函数的可用值:

1myPromise.then(data => {
2  console.log('Received: ' + data);
3  let moreData = "Another payload";
4  return moreData;
5}).then(data => {
6  console.log(data);
7}).catch(() => {
8  console.log("There was an error");
9});

上面的将记录以下内容在控制台:

1Received: Some payload
2Another payload
Published At
Categories with 技术
Tagged with
comments powered by Disqus