"Bringing together ECMA harmony: a nod to callbacks and generators

Initially, we are exploring uncharted territory here. Although it functions in the latest versions of Firefox, the documentation on MDN is not yet ready at the time of writing. I will address the MDN later on (maybe, as there are numerous areas needing attention), so I will provide a glossary.

The task at hand is to create an Iterator from a callback:

I have a class that takes two callbacks as arguments when constructed. Let's name this instance "listener". This listener continuously invokes the first callback with some argument until the listening is completed, then calls the second callback once.

My objective is to wrap an Iterator around this process, which yields each argument received by the listener from calling the first callback and stops throwing StopIteration as soon as the second one is called.

Here is what I aim for:

var magicIter = new MagicIter();

var listener = new Listener(magicIter.ready, magicIter.finished);

//on another thread, listener calls ready(1); ready(2); finished();

exhaustIterator(magicIter); //loops over magicIter and performs actions.

//listener has called finished, causing magicIter to throw StopIteration
//thus ending the loop in exhaustIterator

Keep in mind that I am executing all of this within an Addon SDK addon, allowing me to utilize promises and other related functionalities. And please spare me any discussions regarding how browsers do not comprehend my intentions ;)

/edit: In case you wonder why I don't just convert everything to callback-based code, have a look and advise me on how to perform this conversion without shedding tears. I will simply encapsulate my main function using the method mentioned here.

Answer №1

If you're looking to implement something similar, consider using stream.js:

var s = new Stream( 10, 
          function () 
            {
            return new Stream();
            } 
        );
            // the head of the s stream is 10; the tail is the empty stream
            s.print(); // prints 10
            var t = new Stream( 10, 
            function () 
                {
                return new Stream( 20, 
                  function () 
                    {
                    return new Stream( 30, 
                      function () 
                        {
                        return new Stream();
                        } 
                                     );
                     }   
                                 );
                } 
                              );

           /*
           the head of the t stream is 10
           its tail has a head which is 20 
           and a tail which has a head which is 30 
           and a tail which is the empty stream
           */

           t.print(); // prints 10, 20, 30

To create an Iterator from a callback, you can do:

var callback_iterator =  new Stream( 1, function () {  
  return new Stream(1);  
  } );  

callback_iterator.add(callback_iterator.tail() ).print();

For further reading:

  • Explore ES6 Iterators, Generators, and Iterables here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it feasible to cancel or clear the queue for a jQuery fadeOut function after a delay is specified? If so,

Can anyone help me out with this question? Is there a way to eliminate the delay in chaining? Mn.Base.TopBox.show = function(timedur){ $('#element').fadeIn().delay(timedur).fadeOut(); } Mn.Base.TopBox.cancelFadeout = function(){ } I&apos ...

What is the most secure approach for defining the file path of an HTML file within an express.js application?

In my directory setup, I have the index.js file located at: path/to/home-page/src/routes This is also where you can find the __dirname. The html file resides at: path/to/home-page/public/bootstrap/Homepage/page.html To serve the html document by relati ...

What exactly are AngularJS module dependencies and how do they work together?

After exploring the tutorial example provided on AngularJs's site ( here) (The main HTML appears to be quite minimal with only ng-view and ng-app=phonecatApp included) Within the app.js file, we find: var phonecatApp = angular.module('phoneca ...

Tips for showcasing timestamps within a Vue.js/Firebase application

In my current project, I am working on developing a chat application using Vue.js and Firebase. The codebase I am referring to can be found at https://github.com/jsfanatik/vuestacks-chat-vue-firebase. I have successfully implemented the Chat component to a ...

Obtain the IDs of the previous and next list items if they exist?

Hey there friends, I've hit a roadblock and could really use your help. I'm trying to figure out how to get the previous and next list items in a specific scenario. Let's say I have a ul with three li elements, and the second one is currentl ...

Using this.setState in ReactJS removes filters

Hey everyone, I've been struggling with a technical issue for the past few days and would really appreciate any hints or solutions. The problem lies in creating a table using the material-table library. Specifically, I need to extract the docID and do ...

How can one transfer information from a client to a server and complete a form using JavaScript?

Can the information be transferred from a client to the server using just JS, then fill out a form on the server, and finally redirect the client to view a pre-filled form? I am considering utilizing AJAX to send a JSON object, but unsure if it will be s ...

Unable to retain the textbox value upon the initial button click in ReactJS

Can you please assist me? I am trying to save textbox data to hooks, but when I click the save button, the data is not immediately saved to my useState. I have to click the save button again in order to save it to the hooks. Here are the relevant code sni ...

Using JavaScript's `Map` function instead of a traditional `for`

My dataset consists of a csv file containing 5000 rows, with each row having thirty fields representing measurements of different chemical elements. I aim to parse and visualize this data using D3js. Upon reading the file, I obtain an array of length 5000 ...

New techniques in VueJS 3: managing value changes without using watchers

I am currently working on coding a table with pagination components and I have implemented multiple v-models along with the use of watch on these variables to fetch data. Whenever the perPage value is updated, I need to reset the page value to 1. However, ...

How come the "colspan" attribute is not functioning properly in my table?

Check out the simple table form I created on jsfiddle. Here is the code snippet: <table> <tr> <td class="field_label">name</td> <td>*</td> <td> <input type="text"> ...

Switch out HTML dynamically using JavaScript/JQuery, embracing the principles of DRY coding

As a newcomer to front-end development, one issue I frequently encounter is avoiding repetition when dynamically generating HTML using JS/jQuery. Imagine you have a DOM object that has various states. Typically, all you need to do with JS is switch betwee ...

JavaScript code must be tailored to reference a JS file based on the specific environment, whether it be Production, Development, or staging

I need to determine which .js file to refer based on the URL of Prod, Dev, and QA environments. For Production URLs (domain.com and www.domain.com), I should refer to prod.js file. For Dev and QA URLs (dev.domain.com and staging.com), I should refer to s ...

Building a hierarchical object structure from an array

I am working with an array of objects that looks like this: const sorted = [ { IsoCode: "EUR", Buy: 1.948, Sell: 1.963 }, { IsoCode: "GBP", Buy: 2.1184, Sell: 2.1894 }, { IsoCode: "USD", Buy: 1.5781, Sell: 1.6484 }, ] and my ...

Send a parameter to a React hook

I am facing an issue with a Component that is using a separate hook. I am unable to pass any value to that hook, which is necessary for my use case. const onEdit = (index: number) => useMediaLinkImage(img => { setNodeImages(imgData => { ...

Tips for stopping links in iOS web applications from launching in a new Safari tab

I am in the process of developing an HTML application specifically for iPads. To enhance user experience, I have added the web app to the homescreen using the "favorite" option. However, I encountered an issue where every internal URL opens in a new Safari ...

Inability to successfully upload batch data within specified criteria using a keyword and conditional statement

My goal is to batch the data, using "Repair" as a separator for the data. Splitting criteria = Repair Copper limit = 2.5 [ {"engineSN":"20","timeRun":"30","Cu":"2"}, {"engineSN": ...

Loading a gallery dynamically using AJAX in a CakePHP application

I am currently working with Cakephp 2.8.0 and I am facing an issue with implementing ajax in my application. I have a list of categories displayed as li links, and upon clicking on a category, I need to remove certain html code, locate the necessary catego ...

Troubleshooting: Why isn't setMetadata working in NestJS from authGuards

When I call my decorators, I want to set metadata for logging purposes. Within my controller, the following decorators are used: @Post("somePath") @Permission("somePermission") @UseGuards(JwtAuthGuard) @HttpCode(200) @Grafana( ...

Issue with JQuery on Mobile Devices: Troubles with Dropdown Menu and Loading Function

Having some trouble with my JQuery code on mobile devices. The drop down menu isn't showing up on an iPhone, the load function isn't working to display the additional PHP page on a Samsung Edge 7, and the drop down doesn't seem to be functio ...