kxz
kxz

Reputation: 63

Running functions synchronously

How would I make it so my requestAddress function is run synchronously? Should I make two functions like this and use callbacks? How would I do the callbacks? I can't seem to understand how to do it for this case.

function requestAddress(urlCombined) {
    request(urlCombined, function (error, response, body) {
        a = JSON.parse(body);

        c = addressInfo.status;

    });
}

function isValid() {

    // Retrieve address from input
    addressGet = $('#address').val();

    // Combine url to get address's information
    var urlCombined = 'websitehere' + something;

    requestAddress(urlCombined);


    //do something
    if (condition met) {
        return true;
    } else {
    return false;
    }
}

if (isValid()) {
    do something
}

Upvotes: 0

Views: 64

Answers (2)

quantong zhao
quantong zhao

Reputation: 61

You can try to resolve it by two callback as you think.

Or just try the new syntax async/await

function requestAddress() {
   return new Promise((resolve, reject) => {
      request(XXX,() =>{   
         // .....
         resolve(c)
      })
   })
}

async function isValid () {
    const res = await requestAddress(XXX)
    if () {} else {}
}

Upvotes: 0

IrkenInvader
IrkenInvader

Reputation: 4050

You can send a callback function to your requestAddress function and call it once the request completes. Send parameters back to it as necessary - I've created the callback function as an anonymous function inside of isValid but it could be a seperate named function if you wish.

function requestAddress(urlCombined, callback) {
    request(urlCombined, function (error, response, body) {
        a = JSON.parse(body);    
        c = addressInfo.status;
        callback(error, response, body);
    });
}

function isValid() {
    // Retrieve address from input
    addressGet = $('#address').val();

    // Combine url to get address's information
    var urlCombined = 'websitehere' + something;

    requestAddress(urlCombined, (error, response, body) => {
      //do something
      if (condition met) {
        return true;
      } else {
        return false;
      }
    });
}

if (isValid()) {
    do something
}

Upvotes: 1

Related Questions