为什么 Promisification 对某些方法失败但不是全部?

Why does Promisification fail for some methods but not all?

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 ... promisification 似乎工作得很好!

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

所以我的问题是为什么 promisification 会因一种方法失败而另一种方法却不会?

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

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

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

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

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

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