Javascript PdfMake:函数getBase64返回未定义的值

Javascript PdfMake:函数getBase64返回未定义的值,javascript,typescript,callback,promise,pdfmake,Javascript,Typescript,Callback,Promise,Pdfmake,我正在使用PdfMake生成一个Pdf文件,并使用getBase46()方法将其编码到base64字符串数组中,如下所示: let base64: string; this.pdf.createPdf(buildPdf(pdfModel)).getBase64( function(encodedString) { base64 = encodedString; console.log(base64); // base64 is not undef

我正在使用PdfMake生成一个Pdf文件,并使用
getBase46()
方法将其编码到base64字符串数组中,如下所示:

 let base64: string;

 this.pdf.createPdf(buildPdf(pdfModel)).getBase64(
      function(encodedString) {
        base64 = encodedString;
        console.log(base64); // base64 is not undefined and is a some string
      }
 );

 console.log(base64); // base64 is undefined here

如何在
函数
外部获取变量
base64

这是一个异步操作,您只能保证该值将在回调函数内部定义。

这是一个异步操作,您只能保证该值将在回调函数中定义。

我最终通过将类的实际上下文
this
)绑定到回调
函数
的上下文来解决该问题,以便在调用结束时也可以设置var
base64

    let base64: string;

    this.pdf.createPdf(buildPdf(pdfModel)).getBase64(
        function(encodedString) {
           base64 = encodedString;
           console.log(this.base64); // this.base64 refers to var on the top
        }.bind(this) // To bind the callback with the actual context
    );

我最终通过将类的实际上下文
this
)绑定到回调
函数的上下文
,从而在调用结束时也可以设置var
base64

    let base64: string;

    this.pdf.createPdf(buildPdf(pdfModel)).getBase64(
        function(encodedString) {
           base64 = encodedString;
           console.log(this.base64); // this.base64 refers to var on the top
        }.bind(this) // To bind the callback with the actual context
    );

这意味着在回调之外没有获取字符串的选项@mcrvazidely您应该使用promissions,但无论如何,字符串都只能在“then”中定义。您必须在该函数内执行操作。这意味着在回调函数外没有获取字符串的选项@mcrvazidely您应该使用promissions,但无论如何,字符串都只能在“then”中定义。您必须在该函数内执行您的操作。也可以在此处查看其他说明:()和Typescript的正式文档:()也可以在此处查看其他说明:()和Typescript的正式文档:()