xml-parsing - Bluebird promise `promisifyAll` 不起作用 - 无法读取属性 `then`

标签 xml-parsing callback promise bluebird node-modules

我正在使用一个使用节点回调约定的节点模块。我想使用 Bluebird Promise 将此模块转换为 API。我不知道如何做到这一点。

下面是我的节点样式回调函数。我想把它转换成 Bluebird 的 promise 。

var module = require('module'); // for example xml2js, or Mongoose
var parseString = xml2js.parseString; 
    parseString(xml, function (err, result) { // the regular API
      if (err) {
       console.log("Error in generation json from xml");
      } else {
       return result;
      }
    });

我用 PromisifyAll 尝试过这种方式但它不工作:
var module = Promise.promisifyAll(require('module')); // for example xml2js
xml2js.parseString(xml)
        .then(function (result) {
            console.log("result = ", result);
        })
        .catch(function (err) {
            console.err(err);
        });

我收到 then is not a function错误。我该如何解决?

最佳答案

当 bluebird 使用 promisifyAll 将模块(如 xml2js)转换为基于 Promise 的 API 时然后它附加一个 Async每个函数名称的后缀并将该函数添加到该对象中:

var xml2js = Promise.promisifyAll(require('xml2js')); // example: xml2js 
xml2js.parseStringAsync(xml) // NOTE THE ASYNC SUFFIX
        .then(function (result) {
            console.log("result = " + JSON.stringify(result));
        })
        .catch(function (err) {
            console.err(err);
        });

当您调用 parseString如果没有 async 后缀,它会调用原始的基于回调的函数。

关于xml-parsing - Bluebird promise `promisifyAll` 不起作用 - 无法读取属性 `then`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30067244/

相关文章:

javascript - 解决函数内部的 Promise 会导致 X(...) 不是函数错误

javascript - 异步测试在实习生中如何工作?

java - 从xml文件中读取数据并存储为键值对

javascript - EasyUI - XML 数据加载到数据网格中

javascript - 分解 Backbone.js set 方法时避免范围陷阱?

Javascript : Will a function call all callbacks for all functions that ever called it?

java - android中使用android.sax解析XML问题

xml - XML 中的 JSON

Javascript 通过本地引用传递回调

angularjs - AngularJS 中的 "$q defered.promise is not a function"错误