Compliance with the properties of the ES6 module

I have a module:

var progress = { val: 0 }; var service = (function(){ function someMethod(){ progress.val++; } return{ someMethod: someMethod }; })(); export {service,progress} 

someMethod will perform an operation that someMethod through the array. I would like to increment progress.val once per iteration. This progress should be observed:

  System.import('components/Service.js') .then(function(M){ self.progress = M.progress; Object.observe(M.progress,function(c){ console.dir(c); }); }); 

Unfortunately, the observers callback is called only once, holding the array of changes with one element per iteration.

How can I call a callback at each iteration?

+5
source share
1 answer

The way object monitoring works.

The observer will shoot at the next tick of the watch with a collection of notes. It does not start synchronously on individual changes as they are created. See Also Object.Observe Synchronous Callback .

To accomplish what you want, one approach is to rewrite your iterator so that it β€œsleeps” each time through the loop to give Object.observe chance to fire. I do not necessarily recommend this exact approach, but as an example:

 function iterate(a, fn) { (function loop() { if (!a.length) return; fn(a.shift()); setTimeout(loop); })(); } 

Now, during this iteration of the loop, any property changes made on the fn observation object will be reported.

You can do the same using promises:

 function iterate(a, fn) { a.reduce((p, e) => p.then(() => fn(e)), Promise.resolve()); } 

If you find yourself in an async / wait environment (this is an ES7 function, but available in transpilers such as Babel), you can also do the following, which under the covers is equivalent to the promises approach above:

 async function iterate(a, fn) { for (i of a) await fn(i); } 

As an aside, you don't need IIFE here. Also, self not declared - I expect a runtime error in the line self.progress = M.progress .

+3
source

Source: https://habr.com/ru/post/1215901/


All Articles