Home Web Front-end JS Tutorial Use Promise to solve code nesting problems caused by multiple asynchronous Ajax requests

Use Promise to solve code nesting problems caused by multiple asynchronous Ajax requests

May 22, 2018 pm 04:37 PM
ajax promise asynchronous

This article mainly introduces the use of Promise to solve the code nesting problem caused by multiple asynchronous Ajax requests. Friends in need can refer to

Questions

When the front-end students were making pages, they made a common mistake: writing down multiple Ajax requests in sequence, and subsequent requests are dependent on the return results of the previous requests. As shown in the following code:

var someData;
$.ajax({      url: '/prefix/entity1/action1',
      type: 'GET' ,
      async: true,
      contentType: "application/json",
      success: function (resp) {
        //do something on response
        someData.attr1 = resp.attr1;
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        //在这个页面里,所有的请求的错误都做同样的处理
        if (XMLHttpRequest.status == "401") {
          window.location.href = '/login.html';
        } else {
          alert(XMLHttpRequest.responseText);
        }
      }
    });
$.ajax({
      url: '/prefix/entity2/action2',
      type: 'POST' ,
      dataType: "json",
      data: JSON.stringify(someData),
      async: true,
      contentType: "application/json",
      success: function (resp) {
        //do something on response
       },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        //在这个页面里,所有的请求的错误都做同样的处理
        if (XMLHttpRequest.status == "401") {
          window.location.href = '/login.html';
        } else {
          alert(XMLHttpRequest.responseText);
        }
      }
    });
Copy after login

The above code has two problems:

*The first is that the execution order cannot be guaranteed, action2 is very likely It was issued before action1 returned, resulting in the parameter someData.attr1 not being transmitted correctly

*Secondly, the code duplication of the two ajax requests was very serious

Thinking

  • The problem of code duplication is relatively easy to solve, especially in your own project. Various parameters can be determined through specifications and encapsulated an ajax method with fewer parameters. That’s fine

//url:地址
//data:数据对象,在函数内部会转化成json串,如果没传,表示用GET方法,如果传了,表示用POST方法
function ajax(url, data, callback) {
    $.ajax({
      url: url,
      type: data == null ? 'GET' : 'POST',
      dataType: "json",
      data: data == null ? '' : JSON.stringify(data),
      async: true,
      contentType: "application/json",
      success: function (resp) {
        callback(resp);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        if (XMLHttpRequest.status == "401") {
          window.parent.location = '/enterprise/enterprise_login.html';
          self.location = '/enterprise/enterprise_login.html';
        } else {
          alert(XMLHttpRequest.responseText);
        }
      }
    });
}
Copy after login

This way only the three necessary parameters of url, data and callback need to be filled in, and the others are fixed

  • Regarding the execution order, you can put the second request in the callback of the first request, in the form:

ajax('/prefix/entity1/action1',null, function(resp){
   //do something on response
   someData.attr1 = resp.attr1;
   ajax('/prefix/entity2/action2', someData, function(resp){
     //do something on response
   }
};
Copy after login

So far the problem seems to be solved perfectly, but it is conceivable that if there are more than two requests, but 4 or 5, and there are other asynchronous operations (such as Vue objects in our page Initialization), there are dependencies between each other. Just such layers of nested brackets can make people dizzy.

We need to find a way to make the expression of asynchronous calls look like synchronous calls.

I happened to read Teacher Ruan Yifeng’s book about ES6 recently, and the user did not insist on compatibility with IE browser, so I chose the Promise solution

Solution

  • Introducing Promise

In fact, modern browsers already have built-in support for Promise, and there is no need for third-party libraries No, only IE doesn't work, so I gave up

  • Modify the ajax wrapper function, call resolve() when successful, call reject() when failed, and return the Promise object

function ajax(url, data, callback) {
  var p = new Promise(function (resolve, reject) {
    $.ajax({
      url: url,
      type: data == null ? 'GET' : 'POST',
      dataType: "json",
      data: data == null ? '' : JSON.stringify(data),
      async: true,
      contentType: "application/json",
      success: function (resp) {
        callback(resp);
        resolve();
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        if (XMLHttpRequest.status == "401") {
          window.parent.location = '/enterprise/enterprise_login.html';
          self.location = '/enterprise/enterprise_login.html';
        } else {
          alert(XMLHttpRequest.responseText);
        }
        reject();
      }
    });
  });
  return p;
}
Copy after login

  • Modify the calling end

ajax('/prefix/entity1/action1',null, function(resp){
   //do something on response
   someData.attr1 = resp.attr1;
}).then(
   ajax('/prefix/entity2/action2', someData, function(resp){
     //do something on response
   }
).then(
   initVue() ;
).then(
   //do something else
)
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

HTTP messages and basic knowledge of ajax

The principle of Ajax cross-domain request (graphic tutorial)

Ajax asynchronous request technology example explanation

The above is the detailed content of Use Promise to solve code nesting problems caused by multiple asynchronous Ajax requests. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Keeping your word: The pros and cons of delivering on your promises Keeping your word: The pros and cons of delivering on your promises Feb 18, 2024 pm 08:06 PM

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

Advanced Guide to Python asyncio: From Beginner to Expert Advanced Guide to Python asyncio: From Beginner to Expert Mar 04, 2024 am 09:43 AM

Concurrent and Asynchronous Programming Concurrent programming deals with multiple tasks executing simultaneously, asynchronous programming is a type of concurrent programming in which tasks do not block threads. asyncio is a library for asynchronous programming in python, which allows programs to perform I/O operations without blocking the main thread. Event loop The core of asyncio is the event loop, which monitors I/O events and schedules corresponding tasks. When a coroutine is ready, the event loop executes it until it waits for I/O operations. It then pauses the coroutine and continues executing other coroutines. Coroutines Coroutines are functions that can pause and resume execution. The asyncdef keyword is used to create coroutines. The coroutine uses the await keyword to wait for the I/O operation to complete. The following basics of asyncio

See all articles