TShrestha
TShrestha

Reputation: 1318

Calling async function on javascript onclick (or any) events

I am trying es6 in js along with async/await.

What i have done is :

html code

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

Js code in seperate example.js file, which is alreay included in html.

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

It works fine with this. But since i have to use await for some other function, inside examplefunction(), I did the normal arrow function to async as under

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

Now i am getting

Uncaught SyntaxError: await is only valid in async function

I am stuck here, what am i doing wrong ? I adopted the above syntax from here. Any suggestion are appreciated. Thanks.

Actual Function:

    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();
            }
        })
    };

Upvotes: 21

Views: 95399

Answers (3)

Pablo Nascimento
Pablo Nascimento

Reputation: 59

I solved using JQuery changing to async on definition: from $('#btn').on('click', function (e) { ... } to $('#btn').on('click', async function (e) { ... } worked!

Upvotes: 0

Ronald Coarite
Ronald Coarite

Reputation: 4726

Use:

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

Upvotes: 24

Ravi S. Singh
Ravi S. Singh

Reputation: 657

Hi Suz try the following code it is working for me.

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');

Uncaught SyntaxError: await is only valid in async function

the above error you got suggests that your feedReducer is not an async function

Make sure the feedReducer returns a Promise. Good luck

Upvotes: 14

Related Questions