troubleshooting Question

Javascript "Promise"s being broken

Avatar of Ralph
RalphFlag for United States of America asked on
jQueryAJAX
9 Comments1 Solution221 ViewsLast Modified:
I hope this doesn't turn into a treatise.

On a click of a link I'm using jQuery to get the counter value next to it to use in an SQL lookup.
That's done in function loadTables(event).
I do some other simple stuff like create a unique # to append to the resulting populated HTML file that I save temporarily.
The AJAX code works fine, returning a valid URL.

Still within that function I call a function clicked_rightmarginTableLink(tablename, rowno, thislink, uniq_file_id) that does the AJAX for me and returns the path to the page I want to .load.

A-synchronicity was causing the null page to load before the AJAX returned, so I bravely/boldly/blundered into "promise"s.

I got my promise code layout c/o the 42 line sample here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

When you see the code, the if/then enclosing the promise and AJAX is to keep other blank forms of same kind loading; for the purpose of seeing something happen when I show my boss later today.

You'll see a commented out jQuery .load that works, so substituting the not-waited-for resolved promise IS certainly my problem.
The two alerts, (containing "new_url=" and "Past .load") both happen before the AJAX is done, even thought I though they would now wait.

What tweak am I missing here?
// =================================================================================================
// As per set up in function RightMargin(), this responds to table links clicked in the right margin

function loadTables(event)  
{
  event.preventDefault() ;
  var thislink=$(this).attr('href') ;              // The URL of the link clicked
  var destination='#' + $(this).data('target');    // The TARGET of the link clicked
  
  var id_of_rowno='#' + $(this).data('link');      // Add'l info in the <input> element
  var rowno = $(id_of_rowno).val() ;               // Reads the value the the counter
  
  var tablename= $(this).data('link');  // Use this value, ~ RtMgn_tablename
  tablename = tablename.substring(6) ;  // to extract the table whose data must be loaded
  
  // getRandomIntInclusive(min, max)                        // Thinking (now) that I'll populate the form
  var uniq_file_id = getRandomIntInclusive(1, 9999999999) ; // and have to save it uniquely before loading it
  
  // This function will do the AJAX and return the page to load the the form populated 
  // after the SQL activity
  // However when I run this, I'm getting the alert messages below as the very first thing,
  // before it even call this function!!!
  // ENTER PROMISES
  
  var new_url = "" ;
  
  if (tablename=="Modem")
    {
    // =================================================================
    var maybe = new Promise(
      
      // The resolver function is called with the ability to resolve or
      // reject the promise
      
      function(resolve, reject) 
      { 
        new_url = clicked_rightmarginTableLink(tablename, rowno, thislink, uniq_file_id) ; 
        resolve(new_url) ;
      }    // EO function for resolve or reject
    ) ;  // EO Promise defined
    
    maybe.then(
        // Log and use the fulfillment value
        function(new_url) {
          alert("new_url="+new_url) ; 

          // Load the file
          // $(destination).load("http://10.139.164.191/Cell_Modems/public_html/temp/modem_table_3671212420.html", function( response, status, xhr ) 
          $(destination).load(new_url, function( response, status, xhr )  
          {
            if ( status == "error" ) 
            {
              var msg = "Sorry but there was an error: ";
              alert( msg + xhr.status + " " + xhr.statusText );
            }  // EO IF
          }) ;  // EO Callback for load AND load method itself
          alert("Past .load") ;
        })
    .catch(
        // Log the rejection reason
        function(reason) {
            console.log('Handle rejected promise ('+reason+') here.');
        });

    
  }  // EO IF "Modem"
  else
  {
    // Load the file  (will be changed from this in the near future, once I get ajax deferred/promised/bleah!)
    $(destination).load(thislink, function( response, status, xhr )  
    {
      if ( status == "error" ) 
      {
        var msg = "Sorry but there was an error: ";
        alert( msg + xhr.status + " " + xhr.statusText );
      }
    }) ; 
  }  // EO else not "Modem"
}  // EO function loadTables(event)

Open in new window


Thank you!
ASKER CERTIFIED SOLUTION
Robert Schutt
Software Engineer

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Log in to continue reading
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform for $9.99/mo
View membership options
Unlock 1 Answer and 9 Comments.
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
The Value of Experts Exchange in My Daily IT Life

Experts Exchange (EE) has become my company's go-to resource to get answers. I've used EE to make decisions, solve problems and even save customers. OutagesIO has been a challenging project and... Keep reading >>

Mike

Owner of Outages.IO
Phoenix, Arizona, United States
Member Since 2016
Join a full scale community that combines the best parts of other tools into one platform.
Unlock 1 Answer and 9 Comments.
View membership options
“All of life is about relationships, and EE has made a virtual community a real community. It lifts everyone's boat.”
William Peck

Member since 2004