15

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();
            }
        })
    };
Tekraj Shrestha
  • 1,228
  • 3
  • 20
  • 48
  • 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. – ADyson Dec 11 '19 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? – ADyson Dec 11 '19 at 13:00
  • 2
    you can't await on a function which is not async and doesn't return a promise. check my answer. – Ravi S. Singh Dec 11 '19 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. – Tekraj Shrestha Dec 12 '19 at 05: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({}); – Tekraj Shrestha Dec 12 '19 at 06:49

2 Answers2

19

Use:

document.getElementById("idButton").onclick=async() => {
  await promiseExample();
};
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Ronald Coarite
  • 4,460
  • 27
  • 31
12

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

Ravi S. Singh
  • 617
  • 8
  • 15