Javascript 使用 Promise 调用带有 Bluebird 承诺库的另一个函数内的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36801700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:34:21  来源:igfitidea点击:

Using Promises to call function inside another function with Bluebird promises library

javascriptnode.js

提问by s1n7ax

I have 3 Node Jsfunctions. What I'm trying to do here is, I want to call normalizeFilePathand get the normalized path, after that check whether a file exist or not with that normalizedFilePathand after all these, create a file if the file doesn't already exist. This is the first day of using promises (Bluebird) and I'm new to Node JSand Java Script. Below code structure is getting complex. Of course this is not a good idea at all.

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

How can i manage promises to implement that concept?

我如何管理实现该概念的承诺?

回答by Роман Парадеев

Let's improve your code in two simple steps.

让我们通过两个简单的步骤改进您的代码。

Promises are meant for async functions

Promises 适用于异步函数

As long as path.normalizeis synchronous, it should not be wrapped in promise.

只要path.normalize是同步的,就不应该包含在 promise 中。

So it can be as simple as that.

所以它可以就这么简单。

var normalizeFilePath = function (filePath) {
  return path.normalize(filePath);
};

But for now lets pretendthat path.normalizeis async, so we can use your version.

但是现在让我们假设path.normalize是异步的,所以我们可以使用你的版本。

var normalizeFilePath = function (filePath) {
  return new Promise(function (resolve, reject) {
    resolve( path.normalize(filePath) );
  });
};

Promisify all the things

承诺所有的事情

Sync is bad. Sync blocks event loop. So, instead of fs.existsSyncwe will use fs.exists.

同步不好。同步块事件循环。因此,fs.existsSync我们将使用fs.exists.

var checkFileExistance = function (filePath) {
  return new Promise(function (resolve, reject) {
    fs.exists(filePath, function (exists) {
      resolve(exists);
    });
  });
};

As You can see, we are wrapping async function that accepts a callback with a promise. It's quite a common concept to "promisify" a function, so we could use a libraryfor that. Or even use fs-promise, that is -- you guess it -- fswith promises.

如您所见,我们正在包装异步函数,该函数接受带有承诺的回调。“promisify”一个函数是一个很常见的概念,所以我们可以为此使用一个。或者甚至使用fs-promise,也就是说——你猜对了——fs带有承诺。

Chaining promises

链式承诺

Now, what we want is making three actions one after another:

现在,我们想要的是一个接一个地做三个动作:

  1. Normalize file path
  2. Check if file already exists
  3. If not, create a directory
  1. 规范化文件路径
  2. 检查文件是否已经存在
  3. 如果没有,创建一个目录

Keeping that in mind, our main function can look like this.

记住这一点,我们的主要功能看起来像这样。

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

Don't forget to add the catchcall so you would not miss any errors.

不要忘记添加catch调用,这样您就不会错过任何错误。