Node.js用生成器和yield来替换promise代码

时间:2016-10-20 21:02:18

标签: javascript node.js promise generator yield

这是带有promise的代码:

    it("#execute()", () => {
        let status = master.getStatus();
        let filename = getTempFile("Attachment-execute.fdb");
        const stmt1 = "create table t2 (n1 integer)";
        const stmt2 = "create table t2 (n1 integer, n2 integer)";

        return dispatcher.createDatabase(status, filename)
            .then((attachment: any) => attachment.startTransaction(status)
                .then((transaction: any) => attachment.execute(status, transaction, 0, stmt1, 3)
                    .then(() => attachment.execute(status, transaction, 0, stmt2, 3))
                    .then(() => transaction.commit(status))
                )
                .then(() => attachment.dropDatabase(status))
            )
            .then(() => {
                status.dispose();
            })
            .catch(() => {
                assert(false);
            });
    });

然后我遵循了这个(https://www.promisejs.org/generators/)技术(编写了异步函数),我的代码现在是:

    it("#execute() - generator", async(function* () {
        let status = master.getStatus();
        try {
            let filename = getTempFile("Attachment-execute.fdb");
            const stmt1 = "create table t2 (n1 integer)";
            const stmt2 = "create table t2 (n1 integer, n2 integer)";
            let attachment = yield dispatcher.createDatabase(status, filename);
            try {
                let transaction = yield attachment.startTransaction(status);
                try {
                    yield attachment.execute(status, transaction, 0, stmt1, 3);
                    yield attachment.execute(status, transaction, 0, stmt2, 3);
                }
                finally {
                    yield transaction.commit(status);
                }
            }
            finally {
                yield attachment.dropDatabase(status);
            }
        }
        finally {
            status.dispose();
        }
    }));

在我看来,这是一个更易读的代码,但我几乎没有在节点项目中看到这种类型的代码。

是因为它是最新功能还是在大型项目中可能会产生副作用?

是否有一个好的npm软件包,这个异步函数已经很好地实现了,所以我不需要复制链接中的代码?

0 个答案:

没有答案