Javascript-TypeError:x在完成时不是函数

时间:2018-07-06 10:27:05

标签: javascript asynchronous async-await

我正在使用webpack和node构建自己的浏览器端javascript sdk。

我建立了一个异步/等待文档功能,该功能只是将文档提交给api。

可以在浏览器中两次调用此函数(如果有第二个图像),但是在第二个文档函数调用中,出现以下错误。

  

TypeError:hsp.document不是函数       完成时

index.html

<script>

hsp = new HSP();

// function called on button click
async function done() {

    try {
         const doc = await hsp.document(transaction, token, url, this.frontBase64);

        console.log(doc);

        // If second image,  submit it also.
        if(this.backBase64) {
            const doc = await hsp.document(transaction, token, url, this.backBase64);

        }

    } catch (er) {
        console.log(er);
    }

}

</script>

sdk.js

async document(transaction, token, url, doc) {

        try {

            this.document = await this.api.submitDocument(transaction,
                token, url, doc);

            if (this.document.response.status !== 200) {

                return {
                    "success": false,
                    "response": this.document
                };

            }

            return {
                "success": true,
                "response": this.document
            };


        } catch (e) {
            return {
                "success": false,
                "response": e
            };
        }
    }

1 个答案:

答案 0 :(得分:1)

显然,document函数是在HSP对象中定义的。

第一次调用它时,通过执行hsp.document并在函数内部执行,this关键字是对您从中调用document函数的hsp实例的引用。

在函数内部,您将用this.document调用返回的任何内容重新影响文档函数中的字段this.api.submitDocument。因此,在第一个函数调用之后,它不再是一个函数。