在 JavaScript 中创建您自己的 Promise

来源:undefined 2025-01-18 01:22:04 1050

深入JavaScript Promise:异步回调机制详解及自定义Promise实现

本文将带您深入了解JavaScript Promise的异步回调机制,并指导您亲自动手创建一个符合Promise/A+规范的Promise类。我们将重点关注Promise/A+规范中关键的规则,构建一个简化但功能完备的Promise实现。

一、核心概念

Promise: 一个带有then方法的对象或函数,其行为符合Promise/A+规范。

立即学习Java免费学习笔记(深入)”;

Thenable: 定义了then方法的对象或函数。

Value: 任何有效的JavaScript值(包括undefined、Thenable或Promise)。

异常 (Exception): 使用throw语句抛出的值。

Reason: 表示Promise被拒绝的原因的值。

二、Promise/A+规范关键规则解读与实现

2.1 Promise状态: Promise必须处于以下三种状态之一:待处理(pending)、已完成(fulfilled)或已拒绝(rejected)。

待处理: 可能转换为已完成或已拒绝状态。 已完成: 不得转换到任何其他状态,且必须有一个值,该值不得更改。 已拒绝: 不得转换到任何其他状态,且必须有一个原因,该原因不得更改。

实现:通过state属性跟踪Promise的状态,并使用value和reason属性存储相应的值和原因。状态转换仅在pending状态下进行。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

class YourPromise {

constructor(executor) {

this.state = pending;

this.value = undefined;

this.reason = undefined;

this.onFulfilledCallbacks = [];

this.onRejectedCallbacks = [];

const resolve = (value) => {

if (this.state === pending) {

this.state = fulfilled;

this.value = value;

this.onFulfilledCallbacks.forEach(callback => queueMicrotask(() => callback(this.value)));

}

};

const reject = (reason) => {

if (this.state === pending) {

this.state = rejected;

this.reason = reason;

this.onRejectedCallbacks.forEach(callback => queueMicrotask(() => callback(this.reason)));

}

};

try {

executor(resolve, reject);

} catch (error) {

reject(error);

}

}

// ...then方法实现 (见下文) ...

}

登录后复制

2.2 then方法: Promise必须提供then方法来访问其当前或最终的值或原因。then方法接受两个可选参数:onFulfilled和onRejected。

onFulfilled和onRejected都是可选参数:如果不是函数,则必须忽略。 如果onFulfilled是函数:在Promise完成之后调用,并以Promise的值作为第一个参数。在Promise完成之前不得调用,且不得多次调用。 如果onRejected是函数:在Promise被拒绝之后调用,并以Promise的原因作为第一个参数。在Promise被拒绝之前不得调用,且不得多次调用。 onFulfilled和onRejected必须作为函数调用(即没有this值)。 then方法必须返回一个Promise。 then可以被多次调用,回调按照调用顺序执行。

实现:then方法需要处理三种状态:pending、fulfilled和rejected。对于pending状态,回调需要入队;对于fulfilled和rejected状态,回调需要立即异步执行。 我们使用queueMicrotask确保回调在下一个微任务队列中执行,满足异步执行的要求。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

then(onFulfilled, onRejected) {

return new YourPromise((resolve, reject) => {

if (this.state === fulfilled) {

queueMicrotask(() => {

try {

const result = onFulfilled ? onFulfilled(this.value) : this.value;

resolve(result);

} catch (error) {

reject(error);

}

});

} else if (this.state === rejected) {

queueMicrotask(() => {

try {

const result = onRejected ? onRejected(this.reason) : this.reason;

reject(result);

} catch (error) {

reject(error);

}

});

} else {

this.onFulfilledCallbacks.push(() => {

try {

const result = onFulfilled ? onFulfilled(this.value) : this.value;

resolve(result);

} catch (error) {

reject(error);

}

});

this.onRejectedCallbacks.push(() => {

try {

const result = onRejected ? onRejected(this.reason) : this.reason;

reject(result);

} catch (error) {

reject(error);

}

});

}

});

}

登录后复制

2.3 catch方法 (可选): 为了方便,可以添加一个catch方法,它等同于then(null, onRejected)。

1

2

3

catch(onRejected) {

return this.then(null, onRejected);

}

登录后复制

三、测试

您可以使用以下代码测试您的YourPromise类:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

const promise = new YourPromise((resolve, reject) => {

setTimeout(() => resolve(success!), 1000);

});

promise

.then(value => {

console.log(fulfilled with:, value);

return next step;

})

.then(value => {

console.log(chained with:, value);

});

const promise2 = new YourPromise(resolve => resolve(immediately resolved!));

console.log(before then());

promise2.then(value => console.log(inside then():, value));

console.log(after then());

登录后复制

本文提供了一个简化版的Promise实现,帮助您理解Promise/A+规范的核心概念和实现细节。 完整的Promise实现更为复杂,需要处理更多边缘情况和规范细节,例如Promise的链式调用、then方法返回Promise的处理等。 但这个简化版本足以帮助您掌握Promise的本质。 希望本文能够帮助您更好地理解和运用JavaScript Promise。

以上就是在 JavaScript 中创建您自己的 Promise的详细内容,更多请关注php中文网其它相关文章!

最新文章