s1n*_*7ax 5 javascript node.js
我有3个Node Js功能.我在这里要做的是,我想调用normalizeFilePath并获取规范化路径,然后检查文件是否存在,normalizedFilePath并且在所有这些之后,如果文件尚不存在则创建文件.这是使用promises(Bluebird)的第一天,我是新手Node JS和Java Script.下面的代码结构越来越复杂.当然,这根本不是一个好主意.
var createProjectFolder = function (projectName) {
};
var checkFileExistance = function (filePath) {
return new promise(function (resolve, reject) {
normalizeFilePath(filePath).then(function (normalizedFilePath) {
return fs.existSync(normalizedFilePath);
});
})
};
var normalizeFilePath = function (filePath) {
return new promise(function (resolve, reject) {
resolve(path.normalize(filePath));
});
};
Run Code Online (Sandbox Code Playgroud)
我如何管理实施该概念的承诺?
让我们通过两个简单的步骤改进您的代码.
只要path.normalize是同步的,它就不应该包含在promise中.
所以它可以这么简单.
var normalizeFilePath = function (filePath) {
return path.normalize(filePath);
};
Run Code Online (Sandbox Code Playgroud)
但是现在可以假装那path.normalize是异步的,所以我们可以使用您的版本.
var normalizeFilePath = function (filePath) {
return new Promise(function (resolve, reject) {
resolve( path.normalize(filePath) );
});
};
Run Code Online (Sandbox Code Playgroud)
同步很糟糕.同步块事件循环.所以,而不是fs.existsSync我们将使用fs.exists.
var checkFileExistance = function (filePath) {
return new Promise(function (resolve, reject) {
fs.exists(filePath, function (exists) {
resolve(exists);
});
});
};
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我们正在包装异步函数,该函数接受带有promise的回调.这是一个非常普遍的概念来"宣传"一个函数,所以我们可以使用一个库.或者甚至使用fs-promise,就是 - 你猜它 - fs用promises.
现在,我们想要的是一个接一个地做三个动作:
牢记这一点,我们的主要功能可能如下所示.
var createProjectFolder = function (projectName) {
normalizeFilePath(projectName)
.then(checkFileExistance)
.then(function (exists) {
if (!exists) {
// create folder
}
})
.catch(function (error) {
// if there are any errors in promise chain
// we can catch them in one place, yay!
});
};
Run Code Online (Sandbox Code Playgroud)
不要忘记添加catch呼叫,这样您就不会错过任何错误.
| 归档时间: |
|
| 查看次数: |
27468 次 |
| 最近记录: |