【问题标题】:jQuery Promise async await in an object对象中的 jQuery Promise 异步等待
【发布时间】:2020-12-17 11:28:55
【问题描述】:

我有一个对象,里面有很多函数。其中一些是ajax调用。这个想法是从另一个地方调用其中一个函数并等待它解决,但我不知道它是否可能,如果我不确定该怎么做。这是代码,因此您可以了解我要做什么。

$(document).ready(function(){
   $(".button").click(function(){
       let some_id = $(this).val();
       let ajax_test = binder.firstLayer['ajaxcall'](some_id);
       console.log(ajax_test);
   });
});

然后我有一个包含我使用的所有函数的对象,其中这个 ajax 调用看起来像这样:

let binder = {
    firstLayer : {
        ajaxcall: function(some_id){
            return new Promise( (resolve, reject) => {
                $.ajax({
                    // all the details
                }).then((response) => {
                    resolve(response);
                });
            });
        }
    }
}

我没有包含关键字 async 和 await 因为我不确定将它们放在哪里。在 ajaxcall 函数的情况下,我尝试将 async 放在 ajaxcall: 之后和 function(some_id) 之前,但是当我放 await 时:

let ajax_test = await binder.firstLayer['ajaxcall'](some_id);

但它不起作用。再说一次,问题是它是否可以按照我尝试的方式完成,如果可以,我做错了什么或放在错误的地方。通过这次尝试,如果我尝试查看响应,我会得到undefined,如果我只是控制台记录response(来自与以前相同的地方),我会得到[object Promise](来自console.log(ajax_test);

【问题讨论】:

    标签: javascript jquery oop promise async-await


    【解决方案1】:

    只要将函数标记为异步就可以使用let ajax_test = await binder.firstLayer['ajaxcall'](some_id);

    $(".button").click(async function(){ ...

    【讨论】:

    • 谢谢老兄!这样可行!!没想到会这么简单! :P 唯一的问题是您放置async 的位置会影响其他功能吗?或者如果他们没有await 应该会造成任何麻烦吗?再次感谢!!!
    • 不会影响其他功能。您只能在 async 函数中使用 await,或者您也可以使用 promise .then() 函数。
    猜你喜欢
    • 2020-03-04
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多