Search code examples
javascriptasynchronousasync-awaites6-promise

async await for function with private variables and methods


I have created a simply function with sub functions that returns balance and you can add an amount to update your balance.

const bankAccount = (initialBalance) => {
  let balance = initialBalance;

  return {
    getBalance: function() {
      return balance;
    },
    deposit: function(amount) {
      balance += amount;
      return balance;
    },
  };
};

const account = bankAccount(100);

account.getBalance();
account.deposit(10);

My question is I want to make this function asynchronous, my question is should the overarching function be wrapped in a promise or do the sub functions need to be wrapped in a promise.

This is the kind of approach I was thinking. Is this correct?

async function bankAccount(initialBalance) {
  let balance = initialBalance;
  return await new Promise((resolve, reject) => {
    if ("some error") {
      reject("something went wrong");
    }
    return {
      getBalance: function () {
        resolve(balance);
      },
      deposit: function (amount) {
        balance += amount;
        resolve(balance);
      },
    };
  });
}

Solution

  • Here's one way you can do this with async methods for deposit and balance. I've simulated asynchronous calls using the sleep method that triggers a response after 2 seconds.

    function sleep(retval, ms = 2000) {
      return new Promise(function (resolve, reject) {
        setTimeout(() => {
          resolve(retval);
        }, ms);
      });
    }
    
    const bankAccount = (initialBalance) => {
      let balance = initialBalance;
    
      return {
        getBalance: async () => sleep(balance),
        deposit: async (amount) => {
          balance += amount;
          return sleep(balance);
        },
      };
    };
    
    // An async IIFE, needed unless we have top-level await support
    (async () => {
      const account = bankAccount(100);
      console.log("Initial balance:", await account.getBalance());
      console.log("Deposit 10, new balance:", await account.deposit(10));
      console.log("Deposit 10, new balance:", await account.deposit(10));
    })();