Javascript自动释放资源(如RAII)

Chr*_*ris 9 javascript raii

我的一般问题是我可以使用哪些技术来确保在Javascript中清理/释放资源?目前,我正在采用C(不使用goto)方法来查找函数中返回或异常的每个执行路径,并确保进行清理.

我的具体示例如下:在Node.js中我在对象成员函数中使用互斥(通过文件锁)(我需要互斥,因为我运行Node.js应用程序的多个实例,并且当不同实例与之交互时具有竞争条件文件系统).

例如,在C++中,我会做类似以下的事情:

void MyClass::dangerous(void) {
     MyLock lock(&this->mutex);
     ...
     // at the end of this function, lock will be destructed and release this->mutex.
}
Run Code Online (Sandbox Code Playgroud)

据我所知,JavaScript不提供任何RAII功能.在C中,我会使用gotos在发生错误时展开我的资源分配,这样我只有一个函数的返回路径.

在Javascript中实现类似效果的一些技巧是什么?

Jam*_*Lay 5

正如其他人可能已经注意到的那样,您会想要使用 try/finally。创建一个包装函数来模拟生命周期范围可能会更适合来自 C++。尝试在 javascript 控制台中运行以下代码以获取其用法示例:

class MockFileIO {
    constructor(path) {
        console.log("Opening file stream to path", path);
        this.path = path;
    }
    destructor() {
        console.log("Closing file stream to path", this.path);
    }
    write(str) {
        console.log("Writing to file: ", str);
    }
}

async function run_with(resource, func) {
    try {
        func(resource);
    } catch(e) {
        throw e;
    } finally {
        resource.destructor();
    }
}

async function main() {
    console.log("Starting program");
    const fpath = "somewhere.txt";
    await run_with(new MockFileIO(fpath), (f) => {
        f.write("hello");
        f.write("world");
    });
    console.log("returning from main");
}

main();
Run Code Online (Sandbox Code Playgroud)