Leveraging yield in Angular (ES6)

I have been experimenting with ES6 and attempting to use yield in conjunction with an angular request. However, I am encountering some unexpected behavior. When I write var data = yield getData();, the output is not what I had anticipated. Instead of receiving

{"value":"its working!","done":true}
, I am getting
{"value":{"$$state":{"status":0}},"done":false}

Let me share my code with you.

index.html

<!DOCTYPE html>
<html ng-app="app">
  <body ng-controller="bodyCtrl">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js"></script>
    <script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script>
    <script src="https://google.github.io/traceur-compiler/src/bootstrap.js"></script>
    <script>
        angular.module('app', []);
angular.module('app')
  .controller('bodyCtrl', function ($scope, $http, $q) {
  var getData = function () {
    var deferred = $q.defer();

    $http.get('data.json').then(function (response) {
      console.log(response.data.myData);
      deferred.resolve(response.data.myData);
    });

    return deferred.promise;
  };


  var myGen = function*(){
    var data = yield getData();
    var two = yield 2;
    var three = yield 3;
    console.log(data, two, three);
  };


  var gen = myGen();
  console.log(JSON.stringify(gen.next()));
  console.log(JSON.stringify(gen.next()));
  console.log(JSON.stringify(gen.next()));
  console.log(JSON.stringify(gen.next()));
});
    </script>

  </body>
</html>

data.json

{"myData": "its working!"}

Result

{"value":{"$$state":{"status":0}},"done":false}
{"value":2,"done":false}
{"value":3,"done":false}

{"done":true}

If anyone could provide a brief explanation, it would be greatly appreciated!

Answer №1

You might be doing it incorrectly. ES6 generators actually yield values one at a time, not all at once, as per demand. They do not wait for promises to resolve. If you wish to make use of your generator for asynchronous operations in a synchronous manner, you need to wrap your code within a co function:

co(function*() {
    var gen = myGen();
    console.log(yield gen.next());
    console.log(yield gen.next());
    console.log(yield gen.next());
    console.log(yield gen.next());
})();

You can find the realization of co function here:

and more (in some implementations, immediate execution is not necessary)

For further understanding, refer to the answers provided in this question on Stack Overflow.

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

Acquire the text within an anchor tag using JavaScript

Is it possible to invoke a search for all links on my Wordpress blog? I'm not sure if my idea is correct. Currently, I am using an Ajax call for another search on this site. How can I extract the text from a hyperlink HTML tag? For example: <a href ...

Live Update Google Sheet Data to JSON Without Reloading Web Page

This particular function is executing smoothly. My main concern lies in updating a DOM element without reloading the webpage, if any alterations are made to the data on a Google sheet I am utilizing a JSON file from Google sheets: https://spreadsheets.g ...

Restrict the width of an absolutely positioned element to the width of its

FIDDLE I have a situation where I need to position an element absolutely, like a drop-down menu. However, when the window is resized and becomes narrow, there is not enough space for it. My requirements are: - The right edge of the dropdown should not g ...

Adding a countdown timer plugin from jQuery into a Blogger template

Currently, I am utilizing the 'simple' template on Blogger to build my blog. My goal is to incorporate a countdown timer into the design. After conducting some research, it appears that the most efficient method (that also allows for customizatio ...

SyncHistory middleware for Isomorphic React-Router-Redux

The usage of syncHistory from react-router-redux involves passing the argument browserHistory from react-router. However, when attempting to call syncHistory(browserHistory) on the server, it does not function as expected. The objective is to establish a s ...

Using JavaScript to dynamically insert HTML content and create a toggle effect

Within a div, I have a collection of large images that I am attempting to insert into another div using JavaScript toggle functionality. Please test the code snippet provided below. $(".toggleimages").on("click", function(e) { e.preventDefault(); ...

Steps to assign the identifier as the current index in the v-for iteration

Struggling to assign the id based on the index of a v-for loop. I attempted: <li v-for="(item, index) in items" v-bind:key="item.id"> <p>{{item.name}}</p> <input id= {{index}} type= "number"> < ...

Suggestion for implementing numerous ajax countdown timers (one call per second)

I am currently developing a system with 100 countdown timers that each make an ajax call every second to retrieve the endTime from the database and update the countdown time. The reason for calling this every second is because the endTime can be altered. ...

Learning to extract URL parameters in ReactJS is a valuable skill

I am facing an issue with my React components - App and Contact. I need to display the ID on the contacts page that is passed through the route. However, when I use console.log(this.props) in the Contact component, it returns an empty object. import React ...

Creating a webpage using webkit technology

As someone new to web development, I am eager to create a website that is user-friendly on both desktops and mobile devices. Recently, I stumbled upon a site with impeccable design and functionality using what appeared to be "screen webkit". I'm curi ...

The placement of the button is not correct and should be adjusted to the proper position

I have created a webpage with two distinct sections, each occupying the height of the viewport. The first section contains a 'work' button in the center. Upon clicking this button, it disappears and is replaced by some links. The same functionali ...

Interpret the ng-model data into the input field

My challenge involves translating a value within an input. The input is disabled to prevent users from typing text into the textbox. Currently, the data is entered using ng-model and appears as shown below: <input ng-model="reason" ng-disabled="true" t ...

What could be the reason for the absence of {{ list.title }} on display

I'm currently learning how to develop my first MEAN stack app by following a tutorial on YouTube. However, I've encountered an issue where the title of the list is not displaying correctly. I'm using Insomnia to create the lists. Here's ...

Using varying data types in a byte array with Node.js

I am facing a challenge where I need to create a byte array containing different data types. For instance, the array will include Byte (0-100), Byte (0-10), Two bytes (-30 to +100), Bool (0/1), Byte, and Two Bytes (0-300). The client will receive this byt ...

The amazing magnific popup boasts a pair of close buttons

I recently started working on integrating a front-end HTML theme with a back-end Laravel app. Oddly enough, I noticed that the popup modal is displaying two close x buttons instead of just one. Despite my efforts, I have been unable to pinpoint what exactl ...

What steps can be taken to turn off specific warning rules for CSS mode in ACE editor?

Utilizing the Ace Editor (through Brace and React-Ace) is a key aspect of my project. In our implementation, we specify the editor's mode as "css" and integrate it into our webpage. While this setup functions correctly, we have observed that some of ...

Ensure all checkboxes are selected in AngularJS

As a newcomer to AngularJS, I need some assistance with the following: https://i.sstatic.net/B0K2J.png When the user clicks on the "All" link, I want all 11 checkboxes to be checked. Conversely, when the user clicks on the "None" link, I want all 11 chec ...

The JQuery onchange event functions as expected multiple times within JSFiddle, but seems to only fire once in the

A jQuery (1.11.1) script has been implemented on a business catalyst site cart page to show or hide a message based on the dropdown option selected by the user. The script functions correctly multiple times in jsfiddle at http://jsfiddle.net/NathanHill/462 ...

Troubleshooting: Issues with jQuery Dropdown Menu

I'm currently working on a website that includes a settings feature with a button. My goal is to have the options and other links display in a dropdown menu when hovered over. Although I have written what I believe to be the correct code, it's no ...

Performing an HTTP GET Request with HTML/JavaScript and JQuery

I am endeavoring to initiate an HTTP GET request from my HTML page. The backend of the application is constructed using PHP and the Laravel 4 framework (for PHP). The API's backend is functional. I have conducted tests using the curl command in my Ma ...