Reconnect and promiseIfy after ajax request fails

I remember when I was looking for an internship, I was asked a question. How to resend the request after the front end fails to send the request.

Take ajax as an example:

	let num = 0;
    function ajaxReconnection() {
    
    
      $.ajax({
    
    
        url: "http://localhost:3000",
        method: "GET",
        success: (result) => {
    
    
          console.log("这里输出result:", result);
        },
        error: (error) => {
    
    
          console.error("这里请求失败了:", error);
          if (num < 5) {
    
    
            setTimeout(() => {
    
    
              console.log("失败后尝试重连:", num++);
              test();
            }, 1000);
          } else {
    
    
            console.log("重连次数超过5次,停止重连");
          }
        },
      });
    }

Here, by the way, a promiseIfy changes the writing of functions like success and error in ajax to promise.

function promiseIfy (fn){
    
    
	return function (obj){
    
    
		return new Promise((resolve,reject)=>{
    
    
			obj.success = function (value){
    
    
				resolve(value)
			};
			obj.error = function (error){
    
    
				reject(error)
			}
			fn(obj)
		})
	}
}
promisedAjax = promiseIfy($.ajax)
promisedAjax(obj).then((value)=>{
    
    
	console.log(value)
},(error)=>{
    
    
	console.error(error)
})

Guess you like

Origin blog.csdn.net/qq_42535651/article/details/108916204