【问题标题】:Why does Promisification fail for some methods but not all?为什么 Promisification 对于某些方法但不是全部失败?
【发布时间】:2016-09-14 19:13:34
【问题描述】:

jsonix 库不遵循 first argument must be an error 约定,所以我决定使用 bluebird 并像这样承诺它:

    return new Promise(function(resolve, reject) {
      try {
        unmarshaller.unmarshalString(xmlResponse,
          function (unmarshalled) {
            ...
            resolve(unmarshalled);
          });
      }
      catch (error) {
        reject(error);
      }
    });

但这会无限期地挂起!而如果我只是将xmlResponse 保存到一个文件中,然后用不同的方法处理它:unmarshalFile ... 承诺似乎工作得很好!

    return new Promise(function(resolve, reject) {
      try {
        unmarshaller.unmarshalFile('test1.xml',
          function (unmarshalled) {
            ...
            resolve(unmarshalled);
          });
      }
      catch (error) {
        reject(error);
      }
    });

所以我的问题是,为什么一种方法的承诺会失败,而另一种方法则不会?

【问题讨论】:

    标签: bluebird jsonix


    【解决方案1】:

    当我查看the code for jsonix 时,我看不到.unmarshalString() 的任何回调函数,而查看实现时,实现中没有任何异步,也没有调用回调的任何内容。它只是直接返回答案。所以,该函数是同步的,而不是异步的,它的值直接作为返回值返回。

    作为参考,.unmarshalURL().unmarshalFile() 接受回调并有异步实现 - .unmarshalString() 只是不同。

    因此,您根本不需要对 unmarshaller.unmarshalString(xmlResponse) 使用 Promise。您可以只返回直接值:

    return unmarshaller.unmarshalString(xmlResponse);
    

    如果您想将其包装在所有三个方法之间接口一致性的承诺中,您可以这样做:

    try {
        return Promise.resolve(unmarshaller.unmarshalString(xmlResponse));
    } catch(err) {
        return Promise.reject(err);
    }
    

    或者,您可以使用 Bluebird 的 Promise.method() 为您包装:

    return Promise.method(unmarshaller.unmarshalString.bind(unmarshaller, xmlResponse));
    

    【讨论】:

      【解决方案2】:

      免责声明:我是Jsonix的作者。

      unmarshalURLunmarshalFile 是异步的(并且必须是),但 unmarshalStringunmarshalDocument 不是异步的(并且不必是)。

      【讨论】:

      • 谢谢分享,现在我只是觉得…… dum da dum dum DUMB!
      猜你喜欢
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 2021-01-23
      • 1970-01-01
      • 2011-03-23
      • 2017-05-15
      相关资源
      最近更新 更多