javascript - 在 javascript 中实现 promise 类

标签 javascript node.js ecmascript-6 promise

我正在尝试使用 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)必须返回一个新的 APromisecb 时解决函数被调用。

完整且符合 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/

相关文章:

javascript - 我可以仅在某些条件下添加 React 输入事件处理程序吗?

javascript - Angular 应用程序转移到版本 6 错误 : 'Global is not defined'

javascript - 数据重复并且输出显示两次。可能存在传播错误

javascript - 选择某些值并在 ES6 中按字母顺序排序

javascript - Apple 取消了仅在网络应用程序中在 ios 6 上流式传输 shoutcast 和 icecast 的可能性?

javascript - 第 3 行第 63 列错误 : Space required after the Public Identifier when parsing HTML to XML

node.js - LUIS 中的日期范围

javascript - 如何导入使用 ES2015 语法的文件导出的所有内容?有通配符吗?

JavaScript Date() 在时区之间发生故障?

node.js - 我可以使用 Firebase Cloud Functions 隐藏 JavaScript 代码吗?