简体   繁体   中英

Nodejs - Waiting for a variable: Callbacks

I understand that using callbacks will mean that the function will wait until a result has been returned before returning the result but what if I want to execute further code?

Below is an example of what I am trying to execute. isAvailable checks if someone has a sufficient balance in their account and returns true if they can withdraw their money.

My problem is that this function executes asynchronously so it doesn't wait for the balance to be returned before the if statement is executed.Should I separate the if statement to another function and use a callback to wait for the balance? If so, how would I do so?

function isAvailable(user, withdrawal, callback) {
  var balance = getBalance(user, callback);
  if (withdrawal > balance) {
    callback(false);
  } else if (withdrawal < balance) {
    callback(true);
  } 
}

I understand that using callbacks will mean that the function will wait until a result has been returned before returning the result

No. Being asynchronous means that they return (nothing) immediately, but later call the callback function with the result.

In your example, you'll get the balance not as the return value of getBalance , but as the argument to the call to the callback function that you should pass as the second argument:

getBalance(user, function(balance) {
    …
});

Inside there, you will place the further code to execute:

function isAvailable(user, withdrawal, callback) {
    getBalance(user, function(balance) {
        if (withdrawal > balance) {
            callback(false);
        } else if (withdrawal < balance) {
            callback(true);
        } else { // if (withdrawal == balance)
            callback(null); // don't forget this
        }
    });
}

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