2

I wander if it's possible to use arrow function with generators like this:

app.use( *() => {
 ...body of function
});

Thanks!

asked Jul 21, 2017 at 7:56
5
  • 2
    Did you try running it ? Commented Jul 21, 2017 at 7:58
  • Ok, you're ironic... and how should syntax looks like? Commented Jul 21, 2017 at 8:09
  • Yes I am, you're basically asking if you can run the code you wrote, go ahead, try it yourself and see what happens ! Then, when you'll see it doesn't work, either do your own searches, or look at @hsz 's answer. Commented Jul 21, 2017 at 8:14
  • 1
    If needed, you can easily omit generator function name to achieve anonymous function, like app.use(function*() { /* body of generator */ }). More discuss here: stackoverflow.com/a/34108006/7878274 Commented Jul 21, 2017 at 8:15
  • Yes, but for arrows function maybe works like *() => {}" or "()* => {} and so on.. You see? It's difference to be smart and think you're smart... Commented Jul 21, 2017 at 8:16

2 Answers 2

3

No, it's not possible to make it shorter than described in the documentation:

function* name([param[, param[, ... param]]]) {
 statements
}

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

Kaiido
139k15 gold badges266 silver badges333 bronze badges
answered Jul 21, 2017 at 7:58
Sign up to request clarification or add additional context in comments.

Comments

0

You can, but not really in a nice way. It's not shorter and does not look that pretty. Check this out:

function* iterable(arg) {
 yield* [];
}
async function* asyncIterable(arg) {
 yield* [];
}
const arrowIterable = arg => {
 return {
 *[Symbol.iterator]() {
 yield* [];
 },
 };
};
const arrowAsyncIterable = arg => {
 return {
 async *[Symbol.asyncIterator]() {
 yield* [];
 },
 };
};

This works because an iterable is basically an object with the Symbol.iterator or Symbol.asyncIterator set to an iterator. A generator is an iterator!

Enjoy!

answered Jan 18, 2023 at 13:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.