0

Hi I am a beginner programmer and I need to run several javascript functions in an order on a page; getcampaignID(), search1(), searchresult(), search2(), searchresult(). I need to retrieve the campaign ID first to send it over to search1(), get the result, then running search2() to get its result next.
I have successfully ran [search1() + searchresult()] before [search2() + searchresult()] by executing the search1() after the </body> tag and adding a setTimeout in searchresult(). However, I am unable to run getcampaignID first without breaking search1() and search2()

My code looks like this: home.html

<script>
getcampaignID() {
    //...make AJAX call to get campaignID
    campaignID = xmlhttp.responseText.trim();
}
getcampaignID(); //run function

searchresult() {
        //...retrieves search results
        //...appends to html div

        setTimeout(function () {
            if (counter == 0) {
                counter = 1;
                search2();
            } else {
                clearTimeout(timer);
            }
        }, 500);
    } //end of searchresults

search1() {
    //...search1 parameters 
    //url=?camid = campaignID
    //campaignID unidentified
}

search2() {
    //...search2 parameters 
    //url=?camid = campaignID
    //campaignID unidentified
}


</script>
<body>
<div id= results1>...</div>
<div id= results2>...</div>
</body>
<script>
         search1();
</script>

Things I have tried:

        getcampaignID() {
            //... all the codes mentioned
            search1() {
                alert("search1 working");
            }
            search2() {
                alert("search2 working");
            }
        }
        search1();

Problem: search1() won't run, no alerts fired.

getcampaignID() {
    var campaignid = "A";
    big(campaignid);
}
big
function (campaignid) {

    //..all codes
    search1() {
        alert("search1 working");
    }
    search2() {
        alert("search2 working");
    }
    search1();
}
search1();

Problem: search1() won't run, no alerts fired.

Summary:
I am looking for a way to add campaignID value in search1(); before search1 runs

Pointy
  • 405,095
  • 59
  • 585
  • 614
Detective merry
  • 384
  • 1
  • 21
  • 1
    You've left out most of the interesting code. – Pointy Dec 05 '16 at 15:22
  • Being custom functions you can give them arguments. Where you declared `function search1(){...}` and in the round brackets an argument `function search1(ID){...};`. When you run it just do `search1(campaignid);` and it will pass the argument as ID and you can use it in your function. – yomisimie Dec 05 '16 at 15:24
  • hey, the code is filled with ebay api terms so I try my best not to use them! I just tried out the editions `search1(campaign){...}` and `search1(campaignid);` and it didn't work I think it's because the function is ran even before I get campaignID from my Ajax call – Detective merry Dec 05 '16 at 15:57

3 Answers3

2

What you need is ES6 Promises. Using Promises you could chain them using .then() method and run them one after another and handle results in chain.

Using promises you could write something like

Promise.resolve().then(
    search1();
).then(
    doSomethingWithResults(results);
).then(
    // ....
);

You could find a good introduction to Promises here: https://davidwalsh.name/promises

ZedXter
  • 163
  • 1
  • 6
  • And for compatibility across browsers, use a Promise polyfill/library, like https://github.com/petkaantonov/bluebird bluebird or q. – SethWhite Dec 05 '16 at 15:26
1

You can achieve what you are asking with Promises. They can take a little bit of getting used to, but once you get the hand of it, it makes the asynchronous control flow you are having issues with really simple.

If you used a library to perform your AJAX requests, that returned a Promise itself like Fetch, you could write your code like this:

//Fetch will return a promise the resolves with a value of your campaign ID
fetch('http://endpoint.com/campaign')
    .then(campaignId => {
        //You can pass that ID to each of your searches. 
        //Promise.all will resolve with an array containing results from each function you passed in, in that order.
        return Promise.all([search1(campaignId), search2(campaignId)]);
    })
    .then(results => {
        //Search 1 was the first promise we passed to Promise.all
        let search1Results = results[0];
        //Search 2 was the second promise we passed to Promise.all
        let search2Results = results[1];

        //process the results
    });
BubbleHulk
  • 78
  • 8
0

So there are some possibilities:

  1. Nest the functions. Run search2() inside the callback of search1().
  2. Use jQuery and .defer();
  3. Learn about promises and do same as 2. but without jQuery :)
campino2k
  • 1,618
  • 1
  • 14
  • 25