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();
}
})
};
Use
document.getElementById("idButton").onclick=async ()=>{
// await promiseExample();
};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With