The combination of Ajax and promise use method sharing

Source: Internet
Author: User
This article mainly share with you the use of Ajax and promise method, the need to rely on the completion of the AJAX request can be used promise guarantee the execution order A second request is sent after the first request is returned correctly. Hope to help everyone.

/*  define an AJAX request using promise, where the  request URL in the jquery parameter is required */const ajaxpromise=  param + = {  return new Promise ((Resovle, reject) = {    $.ajax ({      "type":p Aram.type | | "Get",      "async":p Aram.async | | true,      "url":p aram.url,      "data":p Aram.data | | "",      "Success": res = = {        Resovle (res);      },      "error": Err = {        reject (err);      }    )  })} /*   The first request */let Step1 = () = {    Ajaxpromise ({      "url": "",    }). Then (res = {        Console.log (" The first request correctly returns ==> "+res");          Step2 (res);      }). catch (err + = {        Console.log ("First request Failed")}      )} /*   Second request */let Step2 = (res) + {    ajaxpromise ({      "type": "Get",      "url": "",      "data": {"name": RES}    ). Then (res = {        Console.log ("Second request correctly returns ==>" +res))      . catch (err + = {        Console.log ("Second request failed ==>" +err)      })} Step1 ();

Native JS Write Ajaxpromise object

Const Ajaxpromise =  param = {  return new Promise ((Resovle, reject) = = {    var xhr = new XMLHttpRequest ();    xhr.open (Param.type | | "Get", Param.url, true);    Xhr.send (Param.data | | null);    Xhr.onreadystatechange = () = {     var done = 4;//ReadyState 4 indicates that a request has been sent to the server     var OK = $;//status 200 means that the server returns     if (xhr.readystate = = = done) {      if (xhr.status = = = OK) {        Resovle (Json.parse (Xhr.responsetext));      } else{        Reject (Json.parse (Xhr.responsetext);}}}  )}

Some points about the use of promise:

    1. How to use: first create a Promise object new Promise (), determine the execution success or failure based on business requirements, successfully call Resovle (), and fail to invoke reject ().

    2. The then (onfulfilled,onrejected) of the Promise object has two parameters, executed successfully onfulfilled, failed execution onrejectd

      P.then (function (value) {   //Fulfillment succeeded  }, function (reason) {  //rejection failed});//But usually catch () is used to catch the failure, The previous segment code is usually written as: P.then (function (value) {    //Fulfillment success}). catch (function (reason) {    //rejection failed})
    3. Then () of the Promise object returns a new Promise Object

Related recommendations:

Small program promise simplifies callback instance sharing

How the promise of jquery is used correctly

Simple usage of Promise objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.