markjreed

markjreed

Modern Asynchronous JavaScript: using variable name inside its iterator? (page 7)

Within the body of the asynchronous iterator, the code uses srcArr to refer to the array it’s being called on; since it’s a named function and not an arrow func, why not usethis instead? Seems like that would be less brittle and more general.

0 758 1

Marked As Solved

Faraz

Faraz

Author of Modern Asynchronous JavaScript

Hi Mark,

Thanks for reading my book! Because we have a nested function in the iterator, this would refer to next() rather than srcArr. If you replace srcArr with this at line 11 and 16 you’ll get an error.

One workaround is to write const self = this; at the top level of the iterator and replace srcArr with self, like this:

const srcArr = [
  'https://eloux.com/async_js/examples/1.json',
  'https://eloux.com/async_js/examples/2.json',
  'https://eloux.com/async_js/examples/3.json',
];

srcArr[Symbol.asyncIterator] = function() { //<label id="code.asyncIterator"/>
  let i = 0;
  const self = this;
  return {
    async next() {
      if (i === self.length) { //<label id="code.length"/>
        return {
          done: true
        };
      }
      const url = self[i++];
      const response = await fetch(url);
      if (!response.ok) {  //<label id="code.ok"/>
        throw new Error('Unable to retrieve URL: ' + url);
      }
      return {
        value: await response.json(),
        done: false
      };
    }
  };
};

const iterator = srcArr[Symbol.asyncIterator]();

iterator.next().then(result => {
  console.log(result.value.firstName);  // ⇒ John
});

iterator.next().then(result => {
  console.log(result.value.firstName);  // ⇒ Peter
});

iterator.next().then(result => {
  console.log(result.value.firstName);  // ⇒ Anna
});

Let me know if you have any other question :blush:

Popular Prag Prog topics Top

brianokken
Many tasks_proj/tests directories exist in chapters 2, 3, 5 that have tests that use the custom markers smoke and get, which are not decl...
2 1373 2
New
jeffmcompsci
Title: Design and Build Great Web APIs - typo “https://company-atk.herokuapp.com/2258ie4t68jv” (page 19, third bullet in URL list) Typo:...
8 1913 7
New
ianwillie
Hello Brian, I have some problems with running the code in your book. I like the style of the book very much and I have learnt a lot as...
0 1497 3
New
edruder
I thought that there might be interest in using the book with Rails 6.1 and Ruby 2.7.2. I’ll note what I needed to do differently here. ...
9 1170 1
New
alanq
This isn’t directly about the book contents so maybe not the right forum…but in some of the code apps (e.g. turbo/06) it sends a TURBO_ST...
1 1363 7
New
swlaschin
The book has the same “Problem space/Solution space” diagram on page 18 as is on page 17. The correct Problem/Solution space diagrams ar...
1 1067 1
New
patoncrispy
I’m new to Rust and am using this book to learn more as well as to feed my interest in game dev. I’ve just finished the flappy dragon exa...
5 1475 3
New
adamwoolhether
I’m not quite sure what’s going on here, but I’m unable to have to containers successfully complete the Readiness/Liveness checks. I’m im...
5 1387 5
New
taguniversalmachine
Hi, I am getting an error I cannot figure out on my test. I have what I think is the exact code from the book, other than I changed “us...
0 1754 6
New
jwandekoken
Book: Programming Phoenix LiveView, page 142 (157/378), file lib/pento_web/live/product_live/form_component.ex, in the function below: d...
7 1151 10
New

Other popular topics Top

AstonJ
A thread that every forum needs! Simply post a link to a track on YouTube (or SoundCloud or Vimeo amongst others!) on a separate line an...
193 4238 93
New
Exadra37
I am thinking in building or buy a desktop computer for programing, both professionally and on my free time, and my choice of OS is Linux...
36 5138 10
New
AstonJ
SpaceVim seems to be gaining in features and popularity and I just wondered how it compares with SpaceMacs in 2020 - anyone have any thou...
30 3331 14
New
Rainer
My first contact with Erlang was about 2 years ago when I used RabbitMQ, which is written in Erlang, for my job. This made me curious and...
195 6223 96
New
AstonJ
I’ve been hearing quite a lot of comments relating to the sound of a keyboard, with one of the most desirable of these called ‘thock’, he...
14 7486 9
New
AstonJ
Do the test and post your score :nerd_face: :keyboard: If possible, please add info such as the keyboard you’re using, the layout (Qw...
82 6590 31
New
gagan7995
API 4 Path: /user/following/ Method: GET Description: Returns the list of all names of people whom the user follows Response [ { ...
7 2839 4
New
AstonJ
Saw this on TikTok of all places! :lol: Anyone heard of them before? Lite:
13 3704 5
New
PragmaticBookshelf
Build efficient applications that exploit the unique benefits of a pure functional language, learning from an engineer who uses Haskell t...
15 4338 2
New
AstonJ
This is a very quick guide, you just need to: Download LM Studio: https://lmstudio.ai/ Click on search Type DeepSeek, then select the o...
13 2245 10
New