4 ms·
How about an optimistic lock? async function deduct(amt) { var balance = await getBalance(); if (balance >= amt) await setBalanc
by abalone 7y ago
How about an optimistic lock?
async function deduct(amt) {
var balance = await getBalance();
if (balance >= amt)
await setBalance(balance - amt);
var newbalance = await getBalance();
if (newbalance != (balance - amt)) {
await setBalance(balance + amt);
// tell the user the transaction failed...
}
}
- jtsiskin 7y agoThis is getting off topic, but what would probably be best here is a test and set operation: setBalance(expectedBalance, newBalance)
- tlrobinson 7y agoHow about an `updateBalance(updateFn)` that is protected by a mutex: async function deduct(amt) { await updateBalance(balance => { if (balance >= amt) { return balance - amt; } else { throw new Error("not enough balance"); }) }
- wruza 7y agoAnd they call average C developer less experienced in async. The only correct ‘update balance’ operation is: INSERT INTO CashFlow (date, income, expense) VALUES (:date, :income, 0) Get balance: SELECT sum(income)-sum(expense) AS balance FROM CashFlow What modern js still has to reinvent is in-client synchronizing storage which naturally resolves who waits on what (if at all). This is partially simulated by reactjs now by trading in a developer’s comfort at near zero price. All this “await/promise has clear semantics and we think async” is pointless hope because code should never race with itself. Data should, and the storage must be there to kill associated problems once and forever.
- kristiandupont 7y agoOperational transformations are not the "only correct" way to update an integer and it comes with a number of performance and memory/storage consumption implications. >What modern js still has to reinvent is in-client synchronizing storage which naturally resolves who waits on what (if at all) I don't understand what this means but it makes me curious. What would be an example of this in one of the languages that have already "reinvented" it?
- wruza 7y agoSQL. >it comes with a number of performance and memory/storage consumption implications. Instead of selecting sum(), CREATE TRIGGER then and update a singleton on insert. You can even create a view with N recent transactions and catch inserts into it to maintain that N, if you don’t want a full history.