【问题标题】:ajaxStart and ajaxStop equivalent with fetch APIajaxStart 和 ajaxStop 等价于 fetch API
【发布时间】:2016-09-09 04:23:26
【问题描述】:

我正在尝试将我的 API 调用从使用 jQuery ajax 迁移到使用 Fetch API。

我使用 jQuery ajaxStart 和 ajaxStop 在服务器调用期间显示加载微调器。

我正在运行多个并行服务器请求,我希望微调器在第一个请求开始时启动,并在最后一个请求解决时停止。

使用 jQuery 非常简单。但是,我找不到使用 fetch API 的类似技术。 有什么想法吗?

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    您可以使用Promise 来通知fetch 何时被调用并完成

    var params = {
      a: 1,
      b: 2
    };
    
    var data = new FormData();
    data.append("json", JSON.stringify(params));
    
    var currentRequest = new Request("/echo/json/", {
      method: "POST",
      body: data
    });
    
    var start, complete;
    var fetchStart = new Promise(function(_start) {
      start = _start;
    })
    
    var fetchComplete = new Promise(function(_complete) {
      complete = _complete;
    });
    // do stuff when `fetch` is called
    fetchStart.then(function(startData) {
      console.log(startData)
    });
    // do stuff when `fetch` completes
    fetchComplete.then(function(completeData) {
      console.log(completeData)
    });
    
    var request = fetch(currentRequest);
    
    [request, start({
        "fetchStarted": currentRequest
     })].shift()
    .then(function(res) {
      if (res.ok) {
        // resolve `fetchComplete` `Promise` when `fetch` completes
        complete({
            "fetchCompleted": res
         })
      };
      return res.json();
    })
    .then(function(data) {
      document.body.textContent = JSON.stringify(data)
    })
    .catch(function(err) {
       // if error, pass error to `fetchComplete`
       complete({
         "fetchCompleted": res,
         "error": err
       });
    });
    

    jsfiddle https://jsfiddle.net/abbpbah4/18/


    另见Fetch: POST json data

    【讨论】:

      【解决方案2】:

      只需在调用fetch 之前启动您的微调器,然后在finally 中停止它

      state.showSpinner = true;
      Promise.all([fetch(url1), fetch(url2)])
        .then(success => console.log(success))
        .catch(error => console.error(error))
        .finally(() => state.showSpinner = false);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-23
        • 2012-09-18
        • 1970-01-01
        相关资源
        最近更新 更多