Skip to content

Instantly share code, notes, and snippets.

@brigand
Last active March 3, 2018 11:43
Show Gist options
  • Save brigand/6594d2b1f3fdda2d9735b85db43f8f53 to your computer and use it in GitHub Desktop.
Save brigand/6594d2b1f3fdda2d9735b85db43f8f53 to your computer and use it in GitHub Desktop.
ECMAScript Idea: `lazy` operator?
/*
Just an idea, not a formal proposal.
Promises are likely the most common use case for this.
*/
const str = await Promise.fromLazy(
// Pretend the names lazy/yield are something else. Naming is hard.
lazy of `Hello, ${(yield getUser()).name}.
You have ${(yield getMessages()).length} messages.`
);
// Takes the object `lazy of` returns and produces a return value.
// It has the option of executing any of the `yield`d components
// of the expression, and also has the option of evaluating the
// entire expression by calling `execute()`.
Promise.fromLazy = async ({ execute, components }) => {
// components[0] looks like: () => getUser();
const promises = components.map(component => component());
// resolvedValues[0] might be 'Mary'
const resolvedValues = await Promise.all(promises);
// Invokes the expression with the resolved values
return execute(...resolvedValues);
}
// Rough translation
const str = await Promise.fromLazy({
execute: (_1, _2) => `Hello, ${(_1).name}.
You have ${(_2).length} messages.`,
components: [
getUser(),
getMessages(),
]
});
// Promise.params equivilant
const stock = await Promise.fromLazy(lazy of {
symbol: yield getSymbol(),
change: (yield getHoursAgo(24)) - (yield getHoursAgo(0)),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment