单击按钮处理同步和异步功能

时间:2020-08-25 11:07:56

标签: javascript ajax button

我的html页面中有一个按钮,单击该按钮时,我想做两件事-启动进度栏,其次,在后台运行对REST API的ajax调用以获取数据。如果我有一种方法可以完成这两项工作,那么它不会返回,直到REST API返回(我正在使用promise),这样,进度条的目的就消失了。单击按钮如何同时调用这两个功能?

代码:

```javascript``` 

    function showProgress(){
    var x = document.getElementById("progressCircle");
    if (x.style.display === "none") {
                    x.style.display = "block";
    }
  }


function loadData(){
   var promise = new Promise(function(resolve,reject){
   var req = {
                    url: urlWithData,
                    type: "GET",
                    async: false,
                    cache: false,
                    contentType: "text/xml",
                    dataType: "text",
                    success: function (data) {
                        resolve(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        loginfo("Failed to get the data from database" +
                                "textStatus: " + textStatus +
                                "errorThrown: " + errorThrown);
                    },
                    description: "Getting required data"
                };
                $.ajax(req);
                });
       return promise;
}

function getData(){
    showProgress();
    loadData().then(function(data){
       // loading data in html way
    }
}


```html```  

<oj-button id='retrieveData' disabled='false' on-oj-action='[[getData]]'>

<div class="oj-hybrid-padding">
    <div class="oj-panel oj-panel-alt7 oj-margin" >
        <h4 id="result"  data-bind="text:label_result_text"></h4>
        <oj-progress id="progressCircle" type="circle" value="-1" style='display:none'></oj-progress>
        <br/>
        <pre id="dataReturned" style="pointer-events:none;"><oj-bind-text value="[[message]]"></oj-bind-text></pre>
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

如果我有一个方法可以完成这两项工作,那么直到REST API返回(我正在使用promise),它才会返回

是的,确实如此。可能尚未兑现承诺,但函数将返回。如果它是async函数,则返回一个promise。 (如果您返回了通过REST API调用对诺言调用.then.catch的结果,它也会返回诺言。)

您还没有向我们展示您的代码,但是您想要的内容如下所示:

function handler(evt) {
    //           ^^^−−−−−− If you need it for anything

    showProgressIndicator();
    startRestAPICall()
    .then(result => {
        // Use the result
    })
    .catch(error => {
        // Handle/display the error
    })
    .finally(() => {
        hideProgressIndicator();
    });
}

实时示例(使用setTimeout模拟REST API调用)

function showProgressIndicator() {
    document.getElementById("loading").classList.remove("hidden");
}
function hideProgressIndicator() {
    document.getElementById("loading").classList.add("hidden");
}

function startRestAPICall() {
    return new Promise(resolve => {
        setTimeout(resolve, 1500, "this is the data");
    });
}

document.getElementById("btn").addEventListener("click", handler);

function handler(evt) {
    //           ^^^−−−−−− If you need it for anything
    this.disabled = true; // Disable the button

    showProgressIndicator();
    startRestAPICall()
    .then(result => {
        // Use the result
        const p = document.createElement("p");
        p.textContent = result;
        document.body.appendChild(p);
    })
    .catch(error => {
        // Handle/display the error
        const p = document.createElement("p");
        p.className = "error";
        p.textContent = String(error);
        document.body.appendChild(p);
    })
    .finally(() => {
        hideProgressIndicator();
        this.disabled = false; // Re-enable the button
    });
}
.hidden {
    display: none;
}
<input type="button" id="btn" value="Click Me">
<div id="loading" class="hidden"><em>Loading...</em></div>

答案 1 :(得分:0)

如果您正在显示加载栏,那么它将起作用:

const buttonClick = () => {
showLoading() // function handling showing the bar on button click
 $.ajax({ // jquery ajax just for representing ajax call, replace with your ajax call

        'url' : 'http://myapi/api',
        'type' : 'GET',
        'data' : {
            myData
        },
        'success' : function(data) {              
          hideLoading() // function handling hiding the bar on success
        },
        'error' : function(request,error)
        {
            alert("Request: "+JSON.stringify(request));
        }
    });
}