简体   繁体   中英

JavaScript multiple promise issue with $.get

function getHiddenTable(){
    var url = ".......";
    var apptoken = "blahblah";
    return $.get(url, {
        act: "API_DoQuery",
        clist: "7.8.6",
        data: apptoken
    });
}

function getRprTable(){
    var url = "........";
    var apptoken = "blahblah";
    return $.get(url, {
        act: "API_DoQuery",
        clist: "3.60",
        data: apptoken
    });
}

function main(){
    getHiddenTable().then(function(xml_hidden){
        hiddenTable = xml_hidden;
        console.dirxml(hiddenTable);
        return getRprTable();
    }).then(function(xml_rpr){
        rprTable = xml_rpr;
        console.dirxml(rprTable);
    });
}

main();

getHiddenTable() returns a $.get request and getRprTable() also returns a $.get request

Both of these functions return two separate xml files that contain different data. I assign both xml files to two separate global variables so they have scope to other function that I need to use them in. However, both console statements display the initial request from getHiddenTable(). But why? And what can I do to fix this?

Update

Hey guys, thanks for the help. I found out my problem with much frustration and actually utilized $.when, from the person who provided the idea in the comments.

$.when(getHiddenTable(), getRprTable()).done(function(xml_hidden, xml_rpr){
   console.dirxml(xml_hidden[0]);
   console.dirxml(xml_rpr[0]);
});

Accessing the data value of the callback function objects can be done by simply accessing the 0th index.

Thanks

You'll likely want to use Promise.all() to run multiple promises at once and return the results of all the promises once they have all finished.

Example:

Promise.all([getHiddenTable(), getRprTable()])
.then(function(results) {
  let hiddenTable = results[0];
  let rprTable = results[1];
  // do stuff with your results
});

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM