Вызов асинхронной функции для событий javascript onclick (или любых других) - PullRequest
0 голосов
/ 11 декабря 2019

Я пробую es6 в js вместе с async / await.

То, что я сделал, это:

HTML-код

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

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
  }

Теперь я получаю

Uncaught SyntaxError: await действителен только в асинхронной функции

Я застрял здесь, что я делаю не так? Я принял вышеуказанный синтаксис от здесь . Любые предложения приветствуются. Спасибо.

Фактическая функция:

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

1 Ответ

0 голосов
/ 11 декабря 2019

Как это можно сделать,

examplefunction = () => {
    somefunction().then(val => {
        // do something with the value
    })
}
...