我创建了一个简单的函数,它带有返回余额的子函数,您可以添加一个金额来更新您的余额。
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);
我的问题是,我想让这个函数异步,我的问题是,总体函数应该包装在一个承诺或做子函数需要包装在一个承诺。
这就是我想的那种方法。这是正确的吗?
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);
},
};
});
}
您可以使用存款和余额的异步方法来实现这一点。我使用sleep方法模拟异步调用,该方法在2秒后触发响应。
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));
})();
这是正确的使用承诺的方式你只是有一些细节我在下面的代码中修复
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);
},
};
});
}