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);
},
};
});
}
CodePudding user response:
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));
})();
CodePudding user response:
That's right it is the right way to use promises you just have some details that I fixed in the following code
async function bankAccount(initialBalance) {
return await new Promise((resolve, reject) => {
let balance = initialBalance;
if ("some error") {
reject("something went wrong");
}
return {
getBalance: function () {
resolve(balance);
},
deposit: function (amount) {
balance = amount;
resolve(balance);
},
};
});
}