0

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
}
1
  • if request is asynchronous, then no. No matter mow many functions you create, you can never turn asynchronous results into synchronous results. But you change requestAddress to accept a second argument, a callback function, which you can then call in the function (error, response, body) { function. Commented Jan 30, 2018 at 2:46

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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 {}
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.