承诺不适用于节点目录读取文件



我尝试使用 Nodejs 中的 node-dir 模块从目录中读取文件,读取完所有文件后,我将它们发送到 Redis,最后关闭 Redis 连接,所以我使用了 Promise。但是,与 Redis 线路的退出连接总是首先执行,"then"子句似乎不会等到 Promise 解决,导致连接在任何持续发生之前被关闭,我可以寻求您的帮助吗?

new Promise((resolved, failed) => {
nodeDir.readFiles(dirName, options, (err, file, nextCallback) => {
if(err){throw err};
//...logics to get key&value
redisClient.set(key, value);
nextCallback();
});
resolved(); //it finally resolves
}).then(()=>{
redisClient.quit(); //this line never waits, it always executes first
})

让我们看一个类似于你的代码块,找出这里出了什么问题:

new Promise((resolved, failed) => {
setTimeout(function(){}, 3000);
resolved(); 
}).then(()=>{
console.log("DONE");
})

在这种情况下,文本"完成"会立即打印在控制台中。

但是,如果我们像下面这样写,我们会得到一些不同的东西:

new Promise((resolved, failed) => {
setTimeout(function(){
resolved();
}, 3000);  
}).then(()=>{
console.log("DONE");
})

在这种情况下,"完成"将在 3 秒后打印到控制台。你立即解决承诺,这就是这里出错的地方。一旦所有副作用结束,请尝试解决。希望对您有所帮助。

我检查了模块 node-dir 的 API,它实际上提供了一种 readFiles 形式,它提供了一个回调,该回调在处理完所有文件后执行,然后我修改了我的代码以在那里进行解析,它终于按预期工作,非常感谢@Plabon Dutta!

修改后的版本

new Promise((resolved, failed) => {
nodeDir.readFiles(dirName, (err, file, nextCallback) => {
// file handling
}, (err, files) => {
resolved(); //here does the resolve
});
}).then(()=>{
redisClient.quit();
})

这是来自node-dir库的readFiles的通用,承诺返回版本。 请注意,它的唯一工作是返回一个承诺,该承诺在调用完成回调时得到解析。请注意,它不包含 then 块。

// a promise returning form of node-dir readFiles
// pass a file handling callback, but no completion function
function readFilesQ(dirname, options, fileCallback) {
return new Promise((resolved, failed) => {
// this invocation passes a completion function that resolves the promise
nodeDir.readFiles(dirname, options, fileCallback, (err, files) => {
err ? failed(err) : resolved(files)
});
})
}

现在,可以在外部提供文件处理和完成逻辑,具体取决于需要读取文件的上下文。

readFilesQ(someDirname, someOptions, (err, content, next) => {
// handle content for each file, call next
}).then(files => {
// handle correct completion
}).catch(err => {
// handle error
})

最新更新