3 ms·
I went experimenting in a slightly different direction, there's usually a lot of concatenation going on in Javascript with e.g. array manipulation, so I decided
by franciscop 5y ago
I went experimenting in a slightly different direction, there's usually a lot of concatenation going on in Javascript with e.g. array manipulation, so I decided to try to delay the `.then()` as much as possible. So instead of these:
const value = await Promise.all(data.map(op1))
.then(value => value.filter(op2))
.then(value => Promise.all(value.map(op3)));
// OR (a more readable version)
let value = await Promise.all(data.map(op1));
value = value.filter(op2);
value = await Promise.all(value.map(op3));
Now you can do this:
const value = await swear(data).map(op1).filter(op2).map(op3);
I integrated it with my other library `files`, where it's very useful out of the box:
const list = await read('data.csv').split('\n').map(...);
const readmes = await walk('readme.md').map(read);
https://www.npmjs.com/package/swear https://www.npmjs.com/package/swear
https://www.npmjs.com/package/files https://www.npmjs.com/package/files
- mikeyjk 5y agoOoo, I like that. So I'm newer to JS, but this suggests chaining from promises isn't possible, and that's effectively the change you've written?
- franciscop 5y agoIt is possible chaining promises (as in my first example), just just need to wrap it all in a `.then(value => value.[operation]())`, but this way you can just use the `.[operation]()` straight on the data like you would do if there was no promise in the way.