weixin_33699914 2016-09-27 22:06 采纳率: 0%
浏览 84

如何处理较长的请求?

I have an ajax request that may take a long time to return a response.

  $.ajax({
    type: 'POST',
    url: 'some_url',
    data: data,
    processData: false,
    contentType: false,
    headers: {
      "Authorization": 'Token token="'+some_token+'"'
    }
  }).then(function(){
    do_something();
  });

If the request takes a few minutes then everything works as expected. But if the response takes more than about 10 minutes; I get the following error:

jquery.js:9175 POST 'some_url' net::ERR_EMPTY_RESPONSE

But on the server, I can still see that my request is being processed. When that process is finished, I can see that it sends a Completed 201 Created ... response. But I believe since the error is encountered there is nothing listening for the response.

I would like to let the user know the process is finished.

Does any one know the 'best practice' way of handling this?

Any help would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • ?yb? 2016-09-27 22:20
    关注

    Since Ajax is assynchonized, I like to apply a promise. From the top of my head i believe this works like follows:

    function send_ajax(url, data, some_token) {
        var ajax = $.ajax({
            type : 'POST',
            url : url,
            data : data,
            processData : false,
            contentType : false,
            headers : {
                "Authorization" : 'Token token="' + some_token + '"'
            }
        })
    
        return ajax.promise();
    }
    
    
    send_ajax("url","data","some_token").done(function(result) {
        console.log(result);
        do_something();
    });
    

    The result is promised and when returns will execute the function inside done. 10 minutes does seem like an awful long time.

    edit: not the solution As I was pointed out the original Ajax call stays within its context. Meaning that the then() method will handle the returned call. My opted solution does not apply to the OP problem. For reference, the opted solution does handle the asynchronous hurdle when the ajax logic is placed in its own function with a returned value.

    评论

报告相同问题?