【问题标题】:Calling async function on javascript onclick (or any) events在javascript onclick(或任何)事件上调用异步函数
【发布时间】:2020-04-04 18:18:18
【问题描述】:

我正在 js 中尝试 es6 以及 async/await。

我所做的是:

html代码

  <input type="button" onclick="javascript:examplefunction()" />

单独的example.js文件中的js代码,已经包含在html中。

  const somefunction = (...args) => {
    let result =  feedReducer(args);
    // do something
  }

这个很好用。但是由于我必须将 await 用于其他一些函数,在 examplefunction() 中,我做了正常的箭头函数来异步,如下所示

   const somefunction = async (...args) => {
    let result = await feedReducer(args);
    // do something
  }

现在我明白了

未捕获的语法错误:await 仅在异步函数中有效

我被困在这里,我做错了什么?我从here 中采用了上述语法。任何建议表示赞赏。谢谢。

实际功能:

    const preparationManager = async (...args) => {
        console.log(args.length);
        let feed_type = args[0], feed_id = args[1], feed_name = args[2], product_count = args[5];
        let index = args[7] | 0;
        jQuery("#loader").show();
        jQuery.ajax({
            url: 'index.php?option=com_cartproductfeed&task=tranquilizer.formatFeedsToParentChildJson',
            type: 'POST',
            dataType:'json',
            data: {feed_type: feed_type, feed_id:feed_id, feed_name: feed_name, index:index },
            success: function (res) {
                if(res.success === true){
                    if(res.do_repeat === true){
                        args.push(res.index);
                        preparationManager(args[0],args[1],args[2],args[3],args[4],args[5],args[6]);
                    }else{
                        console.log("feedreducer");
                        let result = await feedReducer(args, res);
                        console.log('result',result)
                        console.log("after result")
                    }
                    //window.location.href = base_url + 'index.php/etsy-listings';
                }else{
                    console.log(res);
                }
                jQuery("#loader").hide();
            }
        })
    };

    const feedReducer = async (...args) => {
        jQuery.ajax({
            url: 'index.php?option=com_cartproductfeed&task=tranquilizer.formatFeedsToParentChildJson',
            type: 'POST',
            dataType:'json',
            data: {feed_type: feed_type, feed_id:feed_id, feed_name: feed_name, index:index },
            success: function (res) {
                if(res.success === true){
                    if(res.do_repeat === true){
                        args.push(res.index);
                       let reducerPromise = feedReducer(args[0],args[1],args[2],args[3],args[4],args[5],args[6]);
                       console.log(reducerPromise);
                    }else{
                        //TODO : handle completion of feedreducer
                    }
                    //window.location.href = base_url + 'index.php/etsy-listings';
                }else{
                    console.log(res);
                }
                jQuery("#loader").hide();
            }
        })
    };

【问题讨论】:

  • 您显示的代码不会产生上述错误。你能展示产生问题的实际代码吗?上面的示例令人困惑(函数名称并不完全匹配,例如 examplefunction 与 somefunction),并且它们不会重现问题。如果您不显示导致问题的代码,我们将无法真正帮助您。
  • P.S.你有什么理由还在 HTML 中使用古老的内联 onclick= 处理程序,而不是在 JS 中使用 addEventListener 的不显眼的处理程序?
  • 你不能等待一个非异步且不返回承诺的函数。检查我的答案。
  • @ADyson 这个项目很旧,我没有改变惯例。我还添加了我的查询的实际代码,请看一下,谢谢。
  • 谢谢大家,我终于报错了,我解决了,这是由于ajax中的成功函数回调。我们可以使用 await jQuery.ajax({}); 来解决它

标签: javascript async-await


【解决方案1】:

嗨,Suz,试试下面对我有用的代码。

function feedReducer(args){
    return new Promise((res,rej)=>{
    res(args);
  })
}

const somefunction = async (...args) => {
  let result = await feedReducer(args);
  console.log(result);
  // do something
}

somefunction('hello');

未捕获的语法错误:await 仅在异步函数中有效

您收到的上述错误表明您的 feedReducer 不是异步函数

确保 feedReducer 返回一个 Promise。祝你好运

【讨论】:

    【解决方案2】:

    使用

           document.getElementById("idButton").onclick=async ()=>{
                // await promiseExample();
            };
    

    【讨论】:

      猜你喜欢
      • 2018-08-13
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多