Skip to content

Instantly share code, notes, and snippets.

View rbren's full-sized avatar
🐢
I may be slow to respond.

Robert Brennan rbren

🐢
I may be slow to respond.
  • Fairwinds
  • Boston, Massachusetts
View GitHub Profile
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(reject, ms);
})
}
Promise.race([readFilePromise('index.html'), timeout(1000)])
.then(data => console.log(data))
.catch(e => console.log("Timed out after 1 second"))
Promise.resolve()
.then(_ => api.getItem(1))
.then(item => {
item.amount++;
return api.updateItem(1, item);
})
.catch(e => {
console.log('failed to get or update item');
})
Promise.resolve()
.then(_ => api.getItem(1))
.catch(e => api.createItem(1, {amount: 0}))
.then(item => {
item.amount++;
return api.updateItem(1, item);
})
.catch(e => {
console.log('failed to update item');
})
api.getItem(1)
.then(item => {
item.amount++;
api.updateItem(1, item)
.then(update => {
api.deleteItem(1)
.then(deletion => {
console.log('done!');
})
})
api.getItem(1)
.then(item => {
item.amount++;
return api.updateItem(1, item);
})
.then(update => {
return api.deleteItem(1);
})
.then(deletion => {
console.log('done!');
api.getItem(1)
.then(item => {
item.amount++;
api.updateItem(1, item);
})
.then(update => {
return api.deleteItem(1);
})
.then(deletion => {
console.log('done!');
function readFileAndMaybeLock(filename, createLockFile) {
let promise = Promise.resolve();
if (createLockFile) {
promise = promise.then(_ => writeFilePromise(filename + '.lock', ''))
}
return promise.then(_ => readFilePromise(filename));
}
function readFileAndMaybeLock(filename, createLockFile) {
let promise = Promise.resolve();
if (createLockFile) {
promise.then(_ => writeFilePromise(filename + '.lock', ''))
}
return promise.then(_ => readFilePromise(filename));
}
let p = Promise.resolve('a');
p.then(_ => 'b');
p.then(result => {
console.log(result) // 'a'
})
let q = Promise.resolve('a');
q = q.then(_ => 'b');
q = q.then(result => {
console.log(result) // 'b'
let p = Promise.resolve();
p.then(_ => {throw new Error("whoops!")})
p.then(_ => {
console.log('hello!'); // 'hello!'
})
let q = Promise.resolve();
q = q.then(_ => {throw new Error("whoops!")})
q = q.then(_ => {
console.log('hello'); // We never reach here