我正在尝试使用 javascript 中的可链接 .then()
功能实现一个简单的 promise 类。这是我到目前为止所做的 -
class APromise {
constructor(Fn) {
this.value = null;
Fn(resolved => { this.value = resolved; });
}
then(fn) {
fn(this.value);
return this;
}
}
function myFun() {
return new APromise(resolve => {
// just resolve('Hello'); works but this doesn't
setTimeout(() => { resolve('Hello'); }, 2000);
});
}
const log = v => { console.log(v); };
myFun().then(log).then(log);
这输出-
null
null
代替 'Hello'
2 次。我认为它目前正在忽略 setTimeout()
调用,我应该如何让它工作?
最佳答案
问题
您的代码没有按您希望的方式工作,因为您将异步流与同步流混合在一起。
当您调用 .then()
时,它将返回 this
同步地。自 setTimeout()
是在一段时间(2 秒)后调用的异步函数,this.value
还是null
.
如果想深入了解JS的异步流程,推荐观看this video .它有点长,但非常有帮助。
让你的代码工作
因为我们不知道什么时候setTimeout()
将调用传递给它的函数,我们不能调用和回调依赖于它的操作的函数。我们将这些回调存储在一个数组中供以后使用。
当 setTimeout()
函数被调用 (promise resolves),我们得到了 promise resolution 的结果。因此,我们现在调用所有绑定(bind)的回调。
class APromise {
constructor(Fn) {
this.value = null;
- Fn(resolved => { this.value = resolved; });
+ this.callbacks = [];
+ Fn(resolved => {
+ this.value = resolved;
+
+ this.callbacks.forEach(cb => {
+ cb(this.value);
+ });
+ });
}
then(fn) {
- fn(this.value);
+ this.callbacks.push(fn);
return this;
}
}
function myFun() {
return new APromise(resolve => {
setTimeout(() => { resolve('Hello'); }, 2000);
});
}
const log = v => { console.log(v); };
myFun().then(log).then(log);
链接问题
上面的代码部分解决了这个问题。
当一个回调的结果传递到下一个回调时,就实现了真正的链接。在我们当前的代码中情况并非如此。为了实现这一点,每个 .then(cb)
必须返回一个新的 APromise
当 cb
时解决函数被调用。
完整且符合 Promises/A+ 的实现方式超出了单个 SO 答案的范围,但这不应给人留下它不可行的印象。这是一个 curated list of custom implentations .
更全面的实现
让我们从头开始。我们需要一个类 Promise
实现方法 then
这也返回允许链接的 promise 。
class Promise {
constructor(main) {
// ...
}
then(cb) {
// ...
}
}
在这里,main
是一个将一个函数作为参数并在 promise 被解决/履行时调用它的函数——我们称这个方法为resolve()
.上述功能resolve()
由我们的 Promise
实现和提供类。
function main(resolve) {
// ...
resolve(/* resolve value */);
}
then()
的基本特征方法是触发/激活提供的回调函数cb()
具有 promise 值,一旦 promise 履行。
考虑到这两件事,我们可以重新连接我们的 Promise
类。
class Promise {
constructor(main) {
this.value = undefined;
this.callbacks = [];
const resolve = resolveValue => {
this.value = resolveValue;
this.triggerCallbacks();
};
main(resolve);
}
then(cb) {
this.callbacks.push(cb);
}
triggerCallbacks() {
this.callbacks.forEach(cb => {
cb(this.value);
});
}
}
我们可以用 tester()
测试我们当前的代码功能。
(function tester() {
const p = new Promise(resolve => {
setTimeout(() => resolve(123), 1000);
});
const p1 = p.then(x => console.log(x));
const p2 = p.then(x => setTimeout(() => console.log(x), 1000));
})();
// 123 <delayed by 1 second>
// 123 <delayed by 1 more second>
我们的基础到此结束。我们现在可以实现链接。我们面临的最大问题是then()
方法必须返回一个 promise 同步,它将被异步解决。
我们需要等待 parent promise 解决,然后才能解决 下一个 promise。这意味着不是添加 cb()
对于 parent promise,我们必须添加 resolve()
next promise 的方法,它使用 cb()
的返回值作为其 resolveValue
.
then(cb) {
- this.callbacks.push(cb);
+ const next = new Promise(resolve => {
+ this.callbacks.push(x => resolve(cb(x)));
+ });
+
+ return next;
}
如果最后一点让您感到困惑,这里有一些提示:
-
Promise
构造函数接受一个函数main()
作为论点 -
main()
接受一个函数resolve()
作为论据-
resolve()
由Promise
提供 build 者
-
-
resolve()
将任何类型的参数作为resolveValue
演示
class Promise {
constructor(main) {
this.value = undefined;
this.callbacks = [];
const resolve = resolveValue => {
this.value = resolveValue;
this.triggerCallbacks();
};
main(resolve);
}
then(cb) {
const next = new Promise(resolve => {
this.callbacks.push(x => resolve(cb(x)));
});
return next;
}
triggerCallbacks() {
this.callbacks.forEach(cb => {
cb(this.value);
});
}
}
(function tester() {
const p = new Promise(resolve => {
setTimeout(() => resolve(123), 1000);
});
const p1 = p.then(x => console.log(x));
const p2 = p.then(x => setTimeout(() => console.log(x), 1000));
const p3 = p2.then(x => setTimeout(() => console.log(x), 100));
const p4 = p.then((x) => new Promise(resolve => {
setTimeout(() => resolve(x), 1000);
}))
/*
p: resolve after (1s) with resolveValue = 123
p1: resolve after (0s) after p resolved with resolveValue = undefined
p2: resolve after (0s) after p resolved with resolveValue = timeoutID
p3: resolve after (0s) after p2 resolved with resolveValue = timeoutID
p4: resolve after (1s) after p resolved with resolveValue = Promise instance
*/
})();
// 123 <delayed by 1s>
// 2 <delayed by 1.1s>
// 123 <delayed by 2s>
关于javascript - 在 javascript 中实现 promise 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46577130/