forBlock definition breaks if using async?

237 views
Skip to first unread message

Dummy PG

unread,
Nov 30, 2023, 12:14:24 PM11/30/23
to Blockly
Hi,
I am using blockly v10 and trying to add some api requests within the block generator.
generator.forBlock['my_block'] = async function(block) => {...axios call ...return code}

Is async call not allowed to define a generator code?

I got this error:
Invalid code generated: [object Promise] (at generator.ts:279:11)

How can I add api calls within the generator code?
Thanks

ewpa...@gmail.com

unread,
Nov 30, 2023, 4:02:53 PM11/30/23
to Blockly
As long as I can remember, the generators have never supported asynchronous code. Generator functions for statement blocks are expected to return strings and generator functions for value blocks are expected to return a tuple (array) containing the code and the ordering value. By returning a promise (via the use of async) rather than a string/array the function is violating that contract. A bunch of the internals of generators would need to be updated to support this. However, is there a particular reason why the API call has to happen at the point of code generation? If you know that it has to happen sooner, you could run it before the code generation step occurs. If it's in response to user-provided blocks, then you could have your emitted code include the API call. Can you elaborate on the specific use case?

Regards,
Evan

Dummy PG

unread,
Dec 1, 2023, 11:33:05 AM12/1/23
to Blockly
Hi Evan, 
Thanks for the response. Not sure if that design is intentional, coz one use case I have is that i need to fetch some "list" data that is generated in the backend and put that list as hard coded list in my python code. Having async definition support can really make easy code generator updates for example if i have a lookup reference from either a static json file or database, i can then update the code definition without overhauling the entire code generators. Hope that makes any sense.

ewpa...@gmail.com

unread,
Dec 4, 2023, 2:54:49 PM12/4/23
to Blockly
In that case, you should consider moving the async call prior to calling the generator. For example, in App Inventor some components like CloudDB or ChatBot use a bearer token style authentication and we retrieve that from the server prior to doing any code generation. At that point, it is then available for the synchronous functions used during code generation.

Regards,
Evan

Reply all
Reply to author
Forward
0 new messages