最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using Promises to call function inside another function with Bluebird promises library - Stack Overflow

programmeradmin8浏览0评论

I have 3 Node Js functions. What I'm trying to do here is, I want to call normalizeFilePath and get the normalized path, after that check whether a file exist or not with that normalizedFilePath and 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 JS and Java Script. Below code structure is getting plex. Of course this is not a good idea at all.

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?

I have 3 Node Js functions. What I'm trying to do here is, I want to call normalizeFilePath and get the normalized path, after that check whether a file exist or not with that normalizedFilePath and 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 JS and Java Script. Below code structure is getting plex. Of course this is not a good idea at all.

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?

Share Improve this question asked Apr 22, 2016 at 19:16 s1n7axs1n7ax 3,0696 gold badges29 silver badges62 bronze badges 2
  • Why are you not simply inject the callback (resolve and reject function) into each child function? E.g. function() { return new Promise(function(resolve, reject) { doSomethingOtherAsync(resolve, reject); }); }? Are you searching for simply a working or the "best" solution? – CapCa Commented Apr 22, 2016 at 19:24
  • the best solution actually – s1n7ax Commented Apr 23, 2016 at 2:27
Add a ment  | 

1 Answer 1

Reset to default 13

Let's improve your code in two simple steps.

Promises are meant for async functions

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

So it can be as simple as that.

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

But for now lets pretend that path.normalize is async, so we can use your version.

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.existsSync we will use 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 mon concept to "promisify" a function, so we could use a library for that. Or even use fs-promise, that is -- you guess it -- fs with promises.

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

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 catch call so you would not miss any errors.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论