Skip to content

Instantly share code, notes, and snippets.

@nmors
Last active January 16, 2017 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmors/9150cff301d6c07bdb22da11f2b5f330 to your computer and use it in GitHub Desktop.
Save nmors/9150cff301d6c07bdb22da11f2b5f330 to your computer and use it in GitHub Desktop.
Javascript patterns
Async Javascript Patterns!
const myPromise = () => new Promise((resolve, reject) => {
//...
resolve(/*...*/);
reject(/*...*/);
});
const soAsync = async () => {
try {
const myResult = await myPromise();
const myResult2 = await myPromise(myResult);
console.log('wow')
} catch(error) {
console.error('such reject');
}
}
const P = require('bluebird');
const myPromise = () => new Promise((resolve, reject) => {
//...
resolve(/*...*/);
reject(/*...*/);
});
const suchCoroutine = P.coroutine(function*(req, res){
const someResult1 = yield myPromise(1);
const someResult2 = yield myPromise(2);
const someResult3 = yield myPromise(3);
const someResult4 = yield myPromise(4);
const someResult5 = yield myPromise(5);
res.json({so: async})
})
const P = require('bluebird');
const myPromise = () => new Promise(resolve => {
//...
resolve({
err: null,
resp: 'foo',
});
});
const suchCoroutine = P.coroutine(function*(req, res) {
const { err, resp } = yield myPromise(1);
//... Assign to new variable names
const { err: errorForThing, resp: thingResponse } = yield myPromise(resp);
//... let's use different names!
const { err, resp } = yield myPromise(errorForThing);
//... ES7: rest destructure:
const { ...uberResponse } = yield myPromise(thingResponse);
// lets use our uberResponse
res.json({
so: uberResponse.err,
async: uberResponse.resp
})
})
// DO NOT DO THIS !
fs.readdir(source, function (err, files) {
if (err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function (filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function (err, values) {
if (err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(function (width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
if (err) console.log('Error writing file: ' + err)
fs.readFileSync(source + 'foobar.txt', function (err, file1) {
// do something silly
fs.readFileSync(source + 'foobar2.txt', function (err, file2) {
fs.readFileSync(source + 'foobar3.txt', function (err, file3) {
// SUCH MESS
})
})
})
})
}.bind(this))
}
})
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment