Yield Destructured Variables

Yield Destructured Variables

Hi everyone.
Glad to being here for writing about a proposal for improving Javascript development experience.

Refer to https://tc39.es/ecma262/#sec-generator-function-definitions, with generator functions, we can taking advantages of yield statement which returns as an intermediate value.

IMHO, one thing miss with generator functions : yield destructured variables.

Let me explain my proposal and give you the context of this need :
In the new Vue 3, there is a new concept called Composition API which looks like React hooks.
This new concept answers many reusable and robustness problematics : typings improved, seperation of concern, and centralization of treatments.
One snippet of code is worth a thousand words :

import { reactive } from "vue";

// feature.js
export function useFeature() {
  const state = reactive({
    id: 0,
  })
  const setId = (id) => (state.id = id)

  return {
    id: state.id,
    setId,
  }
}

// component.js
function setup() {
  const { id, setId } = useFeature()
  const name = ref("foo")
  return {
    id,
    setId,
    name,
  };
}

An example of Composition API
Return object of setup function in a component expose a Render Context which is transmitted to the template or JSX.

What you can see, useFeature expose two fields, and we have to get them and return them to the Render Context.

With yield values, we could almost simplify it (if let's say Vue permits setup as a generator function and takes yield values incrementally) :

// component.js
function* setup() {
  const { id, setId } = useFeature()
  yield { id, setId }

  const name = ref("foo")
  return {
    name,
  }
}

As you can see, useFeature fields have to be yield separately.

Here my proposal, with this context :

// component.js
function* setup() {
  yield ({ id, setId } = useFeature())
  const name = ref("foo")
  return {
    name,
  };
}

Hi!

That's valid syntax already. It does exactly what you intend, except for not declaring the two variables it is assigning to.

But I don't see why you would want to use destructuring at all here, you're not using either of the two variables? You could just write

// component.js
function* setup() {
  yield useFeature();
  return {
    name: ref("foo"),
  };
}
1 Like

Thanks for your reply !
Yes, but I want destructuration (and something like that). The syntax is good, but doesn't run because id ans setId doesn't exist.

Yes, I could use this, but Composition API best practices encourages to explicitly expose what we want.
However, this is better than return { ...useFeature } !

By using destructuring, we can choose which field we want.
I suggest something new :

yield { id, setId } = useFeature() which is to interpret as extract id and setId attribute and yield it. Without braces..
With braces, id and setId would be assigned by useFeature.