How do you make javascript code execute *in order*

后端 未结 9 1199
别那么骄傲
别那么骄傲 2020-11-30 05:49

Okay, so I appreciate that Javascript is not C# or PHP, but I keep coming back to an issue in Javascript - not with JS itself but my use of it.

I have a function:

9条回答
  •  伪装坚强ぢ
    2020-11-30 06:20

    One of the best solutions for handling all async requests is the 'Promise'.
    The Promise object represents the eventual completion (or failure) of an asynchronous operation.

    Example:

    let myFirstPromise = new Promise((resolve, reject) => {
      // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
      // In this example, we use setTimeout(...) to simulate async code. 
      // In reality, you will probably be using something like XHR or an HTML5 API.
      setTimeout(function(){
        resolve("Success!"); // Yay! Everything went well!
      }, 250);
    });  
    
    myFirstPromise.then((successMessage) => {
      // successMessage is whatever we passed in the resolve(...) function above.
      // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
      console.log("Yay! " + successMessage);
    });
    

    Promise

    If you have 3 async functions and expect to run in order, do as follows:

    let FirstPromise = new Promise((resolve, reject) => {
        FirstPromise.resolve("First!");
    });
    let SecondPromise = new Promise((resolve, reject) => {
    
    });
    let ThirdPromise = new Promise((resolve, reject) => {
    
    });
    FirstPromise.then((successMessage) => {
      jQuery.ajax({
        type: "type",
        url: "url",
        success: function(response){
            console.log("First! ");
            SecondPromise.resolve("Second!");
        },
        error: function() {
            //handle your error
        }  
      });           
    });
    SecondPromise.then((successMessage) => {
      jQuery.ajax({
        type: "type",
        url: "url",
        success: function(response){
            console.log("Second! ");
            ThirdPromise.resolve("Third!");
        },
        error: function() {
           //handle your error
        }  
      });    
    });
    ThirdPromise.then((successMessage) => {
      jQuery.ajax({
        type: "type",
        url: "url",
        success: function(response){
            console.log("Third! ");
        },
        error: function() {
            //handle your error
        }  
      });  
    });
    

    With this approach, you can handle all async operation as you wish.

提交回复
热议问题