Home Building an object using async ajax calls
Reply: 1

Building an object using async ajax calls

Jim B
1#
Jim B Published in 2017-12-07 20:20:05Z

I need to return a custom object that relies on multiple async jquery ajax calls.

Sample code below:

function BuildMyObject() {
    var bp = null;
    var accountId = getAccountId();
    var signature = getSignature();
    var transactionType = getTransactionType();
    var mode = getMode();
    var merchantIdentifier = getMerchantIdentifier();
    jQuery.when(accountId, signature, transactionType, mode, merchantIdentifier).done(function(rAcctId,
        rSig,
        rTransType,
        rMode,
        rMerchId) {
        bp = new MyObject(
            rAcctId[0],
            rSig[0],
            rTransType[0],
            rMode[0],
            rMerchId[0]);
    });
    return bp;
}

Now, this returns null; as the return statement is firing before the async calls finish. Is there a way to wait untill all the calls are finished before returning the object? If i set the ajax calls to synchronious, it works; but I'd like to avoid that.

Amit Wagner
2#
Amit Wagner Reply to 2017-12-07 21:08:49Z

you can work with Promises or callbacks for scenarios of async functions

//callback example
function BuildMyObject(callback) {
    var bp = null;
    var accountId = getAccountId();
    var signature = getSignature();
    var transactionType = getTransactionType();
    var mode = getMode();
    var merchantIdentifier = getMerchantIdentifier();
    jQuery.when(accountId, signature, transactionType, mode, merchantIdentifier).done(function(rAcctId,
        rSig,
        rTransType,
        rMode,
        rMerchId) {
        bp = new MyObject(
            rAcctId[0],
            rSig[0],
            rTransType[0],
            rMode[0],
            rMerchId[0]);
            )
        callback(bp)
           
    });
   
}


//or with promise

function BuildMyObject() {
    return new Promise((resolve,reject) =>{
        var bp = null;
        var accountId = getAccountId();
        var signature = getSignature();
        var transactionType = getTransactionType();
        var mode = getMode();
        var merchantIdentifier = getMerchantIdentifier();
        jQuery.when(accountId, signature, transactionType, mode, merchantIdentifier).done(function(rAcctId,
            rSig,
            rTransType,
            rMode,
            rMerchId) {
            bp = new MyObject(
                rAcctId[0],
                rSig[0],
                rTransType[0],
                rMode[0],
                rMerchId[0]);
           )
           resolve(bp)
        });

    }) 
  
   
}

BuildMyObject()
.then((bp) =>{
    //do somthing with bp
})

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301597 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO