在Node上排队访问文件系统



我有一个包装器类在我的web应用程序的服务器上管理文件系统访问。

async saveArchiveData(id, data) { /* saving data to the disk using fs */ }
async getArchiveData(id) { /* read data from disk */ }

这些都是用打字稿写的,但为了便于阅读,它们被分解成相关的部分。

这些函数可以这样调用:getArchiveData将尝试访问当前由saveArchiveData保存的数据。在这种情况下,我不希望getArchiveData失败,而是等待数据可用,只返回然后(所以有点像排队那些函数)。对此的最佳实践是什么?谢谢!

使用承诺队列:

constructor() {
this.queue = Promise.resolve();
}
_enqueue(fn) {
const promise = this.queue.then(fn);
this.queue = promise.then(x => void x, _err => { /* ignore */ });
return promise;
}
async _writeData(id, data) { /* saving data to the disk using fs */ }
async _readData(id) { /* read data from disk */ }
saveArchiveData(id, data) {
return this._enqueue(() => this._writeData(id, data));
}
getArchiveData(id) {
return this._enqueue(() => this._readData(id));
}

这将保证_writeData_readData永远不会并发运行(每个类的实例)。如果适合您的应用程序,您可能还希望每个id有一个队列。

所以这个问题叫做"一致性"。通常,这是通过称为"最终一致性"的模式来处理的。在这种情况下,读通常落后于写一小段时间,但足够准确。你所描述的是"很强的一致性"。这意味着阅读器将永远拥有最新的信息。但是构建起来要困难得多,通常只有在绝对必要的情况下才会这样做。

最新更新