23

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();
            }
        })
    };
5
  • 1
    The code you've shown wouldn't produce the mentioned error. Can you show the actual code which produces the problem? The examples above are confusing (function names don't all match, e.g. examplefunction vs. somefunction), and they don't reproduce the problem. We can't really help you if you don't show the code which is causing the issue. Commented Dec 11, 2019 at 12:59
  • P.S. Any reason you're still using archaic inline onclick= handlers within your HTML, instead of unobtrusive ones using addEventListener within the JS? Commented Dec 11, 2019 at 13:00
  • 2
    you can't await on a function which is not async and doesn't return a promise. check my answer. Commented Dec 11, 2019 at 13:16
  • @ADyson This project is old and I haven't changed the convention. Also I have added the actual code ion my query, please have a look at it, thanks. Commented Dec 12, 2019 at 5:12
  • Thanks to you all, I finally go the error and I solved it, It was due to the success function callback in ajax . We could solve it by using await jQuery.ajax({}); Commented Dec 12, 2019 at 6:49

3 Answers 3

26

Use:

document.getElementById("idButton").onclick=async() => {
  await promiseExample();
};
Sign up to request clarification or add additional context in comments.

1 Comment

If the promiseExample() call is the only thing being done on the click event, would it matter if it was just called without the await like onclick=promiseExample?
14

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

Comments

-1

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

1 Comment

This approach does not work for me unfortunately.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.