We help IT Professionals succeed at work.
Get Started

Javascript "Promise"s being broken

Ralph
Ralph asked
on
217 Views
Last Modified: 2016-03-08
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!
Comment
Watch Question
Software Engineer
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 9 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE