什么是 Promise

Promise 是一个在将来未知时间返回异步操作单一结果的对象。

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Promise 有三种状态:

  1. pending: 初始状态,既不是完成也不是拒绝
  2. fulfilled: 完成状态,说明操作已经成功完成
  3. rejected: 拒绝状态,说明操作失败

用法

通过 new 来创建一个 Promise 对象, Promise 有 resolvereject 2个参数,操作完成时调用 resolve, 操作失败时调用 reject

1
2
3
4
5
6
7
8
9
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
}

链式调用

使用 promise.then(successCallback, failureCallback) 来链式调用 promise

使用 promise.catch(failureCallback) 来处理错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
new Promise((resolve, reject) => {
console.log('Initial');

resolve();
})
.then(() => {
throw new Error('Something failed');

console.log('Do this');
})
.catch(() => {
console.log('Do that');
})
.then(() => {
console.log('Do this, no matter what happened before');
});

// Initial
// Do that
// Do this, no matter what happened before

Promise.all

有时我们需要等待所有异步操作都完成之后再进行某些操作,这时我们可以使用 promise.all

虽然 text2 只需要 500 毫秒就能完成,但是代码的结果是 2秒后一起返回 text1text2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const text1 = new Promise((resolve) => {
setTimeout(() => {
resolve({ content: 'I love js'});
}, 2000);
});

const text2 = new Promise((resolve) => {
setTimeout(() => {
resolve(['I like css too!']);
}, 500);
});

Promise
.all([text1, text2])
.then(responses => {
const [text1Content, text2Contect] = responses;
console.log(text1Content, text2Contect)
});

JS sleep 方法

1
2
3
4
5
6
7
8
9
10
11
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
console.log('Taking a break...');
await sleep(2000);
console.log('Two second later');
}

demo();