0

Here is this code with promises:

    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);
            });
    });

I then followed this (https://www.promisejs.org/generators/) technique (wrote the async function) and my code is now:

    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();
        }
    }));

This is a much more readable code in my opinion, but I almost don't see this type of code in node projects.

Is it because it's a recent feature or it may have side consequences in a large project?

Is there a good npm package with this async function well implemented so I didn't need to copy-past the code in the link?

0 Answers0