繁体   English   中英

Javascript获得自定义异步并等待函数工作

[英]Javascript getting custom async and await functions to work

我正在使用webpack和node构建自己的borwserside javascript sdk。

我在SDK中创建了一个简单的身份验证功能。 它是一个简单的回调函数,该函数查询api并以回调形式返回结果是否成功。

sdk.js

  async authenticate(callback) {

        try {

            this.account = await this.repo.authenticate(this.product, this.origin);

            if (this.account.success === false) {
                return callback({
                    "success": false,
                    "response": "Failed To Authenticate"
                });
            }

            return callback({
                "success": true,
                "response": this.account
            });


        } catch (e) {

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

        }

    }

现在在我的浏览器中,我有一个索引文件。 它将实例化对象并调用此函数。

index.html

<script>

hsp = new HSP();

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

    // Works
    hsp.authenticate((res) => {
        console.log(res);
     });

     // DOES NOT WORK
    try {
        const auth = await hsp.authenticate();

        console.log(auth);

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

}

</script>

在上述index.html中的示例中,authenticate的回调版本有效,但是try catch块中的authenticate的await / async版本不起作用。 为什么以及如何使它起作用。

我希望这两个选项都能正常工作。

我收到以下错误。 其中引用了catch块和console.log(er)。

TypeError:t不是t.value处的函数(index.js:41)

您混用了两种方法callbackspromises 使用promises功能更强大,异步函数利用promise,它们使您可以编写基于promise的代码,就好像它是同步的一样,但是不会阻塞主线程。

异步返回值

无论是否使用await,异步函数总是返回一个Promise。 该承诺将通过异步函数返回的任何内容来解决,或者通过异步函数抛出的任何内容来拒绝。

然后在async函数之外使用您的回调或捕获。

sdk.js

async authenticate() {

        try {

            this.account = await this.repo.authenticate(this.product, this.origin);

            if (this.account.success === false) {
                return {
                    "success": false,
                    "response": "Failed To Authenticate"
                };
            }

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


        } catch (e) {

            return {
                "success": false,
                "response": e
            };

        }

    }

index.html

<script>

hsp = new HSP();

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

    // Works (Your callback here in then method)
    hsp.authenticate().then((res) => {
        console.log(res);
     }).cath( err => console.log(er));

     // It Will WORK (Make use of your callback outside of the async function)
    try {
        const auth = await hsp.authenticate();

        console.log(auth);

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

}

</script>

我希望这将有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM