如何从NodeJS Promise返回XML?

时间:2016-09-09 18:47:12

标签: xml node.js function promise

任何人都可以帮助我如何通过此功能返回此xml?

每当我在外面调用此函数时,我都需要返回变量 xmlAssinado

module.exports = { AssinarXML: function(xml, arquivo, data){
certificado.GerarPEM()
.then(function(pem){
  if (pem !== 500){ 
    const transforms = [
      'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
      'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'
    ];
    const infoProvider = (pem) => {
      return {
        getKeyInfo() {
          const cert = this.getCert();
          return `<X509Data><X509Certificate>${cert}</X509Certificate></X509Data>`;
        },
        getCert() {
          const certLines = pem.certificate.split('\n');
          return certLines.filter((e, i) => i && e && e.indexOf('-----') !== 0).join('');
        }
      };
    };

    var signer = new SignedXml();
    signer.addReference(`//*[local-name(.)=\'infNFe\']`, transforms);
    signer.signingKey = new Buffer(pem.key);
    signer.canonicalizationAlgorithm = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
    signer.keyInfoProvider = infoProvider(pem);
    signer.computeSignature(xml);
    **var xmlAssinado = signer.getSignedXml();**

    fs.writeFile(arquivo + '.xml', xmlAssinado, function(err) {
      if(err) {
        console.error("Ocorreu um erro na gravação do arquivo: %s", err);
      }
      else {
        console.log("XML Gerado e Assinado Com Sucesso!");
      }
    });
  } else {
    console.error("Ocorreu na assinatura do arquivo");
  }
})}}

我能做些什么来实现这个目标?

1 个答案:

答案 0 :(得分:0)

从您的方法返回承诺,以便调用者可以通过在此处添加return来访问该承诺链:

 return certificado.GerarPEM()...

然后,在xmlAssinado处理程序的末尾返回.then()

return xmlAssinado;

这将使xmlAssinado值成为您承诺的已解决值。然后,您可以使用带有返回的promise的.then()处理程序来获得所需的解析值,如下所示:

myModule.AssinarXML(...).then(function(xmlAssinado) {
    // you can use the value here
});

执行上述操作不会等待fs.writeFile()在解决之前完成(这将按照自己的进度继续)。如果你需要等待它完成,那么你应该宣传writeFile操作并将其链接到promise链中,这样你只有在完成时才能解决。