【问题标题】:Convert async code to promise将异步代码转换为 Promise
【发布时间】:2015-10-24 16:47:34
【问题描述】:

我使用以下代码,我需要将其转换为 promise,最后返回包含文件配置的对象, 我该怎么做?

 var Promise = require('bluebird'),
      glob = promisifyAll(require("glob")),
      fs = Promise.promisifyAll(require("fs"));

module.exports = {
    parse: function (configErr) {
    glob("folder/*.json", function (err, files) {
      if (err) {
        return configErr(new Error("Error to read json files: " + err));
      }
      files.forEach(function (file) {
        fs.readFileAsync(file, 'utf8', function (err, data) { // Read each file
          if (err) {
            return configErr(new Error("Error to read config" + err));
          }
          return JSON.parse(data);
        });
      })
    })

UPDATE - 在代码中我想从节点项目的特定文件夹中获取 json 文件并将 json 内容解析为对象

【问题讨论】:

  • 你也应该解释一下你实际上想要做什么。
  • @thefourtheye- 我会尽快用您提出的数据更新我的问题
  • @thefourtheye -完成!
  • @shopiaT 解析后忽略它。

标签: javascript node.js promise bluebird


【解决方案1】:

Promisified 函数返回 Promise,您应该使用它们而不是将回调传递给调用。顺便说一句,您的 forEach 循环不能异步工作,您应该为此使用 dedicated promise function

 var Promise = require('bluebird'),
     globAsync = Promise.promisify(require("glob")),
     fs = Promise.promisifyAll(require("fs"));

module.exports.parse = function() {
    return globAsync("folder/*.json").catch(function(err) {
        throw new Error("Error to read json files: " + err);
    }).map(function(file) {
        return fs.readFileAsync(file, 'utf8').then(JSON.parse, function(err) {
            throw new Error("Error to read config ("+file+")" + err);
        });
    });
};

然后你可以导入这个promise,并通过.then附加回调来捕获错误或使用已解析的配置对象数组。

var config = require('config');
config.parse().then(function(cfg) { … }, function onConfigErr(err) { … })

【讨论】:

  • 谢谢我试了一下,我得到错误 undefined is not a function in the .catch(function(err) { ,知道吗?
  • @shopiaT:请记录globAsync 调用的结果,看看它是什么。 Promisification 应该可以在 glob 上正常工作。
  • 我应该如何记录它?
  • 但是我运行的时候怎么出错了,要我改代码吗?
  • 是的,请使用标准调试技术。如果您不想将调试器指向节点,请编辑代码并在适当的位置插入 console.log 语句。
猜你喜欢
  • 2013-07-01
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多