Skip to content

Instantly share code, notes, and snippets.

@JasonCust
Last active February 12, 2018 22:49
Show Gist options
  • Save JasonCust/a5bf90992d4c71722f1c3d0f8212e2fc to your computer and use it in GitHub Desktop.
Save JasonCust/a5bf90992d4c71722f1c3d0f8212e2fc to your computer and use it in GitHub Desktop.
// Helper function to generate random delay
function randomWait() {
return new Promise(resolve => {
setTimeout(resolve, Math.ceil(Math.random() * 1000));
});
}
// The "database"
const dataStore = {
// Records Collection
records: [
{ id: 1, foo: 'expedita odio fugiat', bar: 'eos natus pariatur' },
{ id: 2, foo: 'aspernatur reiciendis dolores', bar: 'illo delectus ut' },
{ id: 3, foo: 'rerum tempore minima', bar: 'qui hic dolor' }
],
// Simulate an async get request
get: async function get(collection, id) {
const obj = this[collection].find(doc => doc.id === id);
// Shallow clone doc to break reference to collection object
return {...obj};
},
// Simulate an async save request
save: async function save(collection, id, obj) {
const index = this[collection].findIndex(doc => doc.id === obj.id);
// "Store" record
return this[collection][index] = { ...this[collection][index], ...obj };
}
}
// Simulated two concurrent fetch and save requests
Promise.all([
dataStore.get('records', 2).then(async record => {
// Simulate a delay
const wait = await randomWait();
record.foo = 'Update';
return dataStore.save('records', 2, record);
}),
dataStore.get('records', 2).then(async record => {
// Simulate a delay
const wait = await randomWait();
record.bar = 'Update';
return dataStore.save('records', 2, record);
}),
]).then(
results => Promise.all(results.concat(dataStore.get('records', 2)))
).then(
([firstUpdate, secondUpdate, curRecord]) => console.log({firstUpdate, secondUpdate, curRecord})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment