It prints "End", "Work 1" and "Work 2" in that order (the work is done asynchronously). But if there are more events like this, the code becomes very complex.
It also prints "End", "Work 1" and "Work 2" (the work is done asynchronously). But, this is clearly more readable than the previous example and in more complex situations it is easier to work with.
In the second line of the code, we use a * with the function keyword. It's called a generator function (or gen function).
在程式碼的第二行,我們使用一個星字號 * 和function關鍵字,它稱為生成器函式(generator function 或 gen function)。
For example, here is a simple case of how gen functions can be useful:
例如,這裡有個簡單的情況,看看gen functions是如何實用:
function* idMaker() { let index = 0; while (index < 5) yield index++; } var gen = idMaker(); console.log(gen.next().value)
We can exit and re-enter generator functions later. Their variable bindings (context) will be saved across re-entrances. They are a very powerful tool for asynchronous programming, especially when combined with Promises. They can also be useful for creating loops with special requirements.
We can nest generator functions inside each other to create more complex structures and pass them arguments while we are calling them. The example below will show a useful case of how we can use generator functions and Symbol.iterators together. Example:
const arr = ['0', '1', '4', 'a', '9', 'c', '16']; const my_obj = { [Symbol.iterator]: function*() { for(let index of arr) { yield `${index}`; } } }; const all = [...my_obj] .map(i => parseInt(i, 10)) .map(Math.sqrt) .filter((i) => i < 5) .reduce((i, d) => i + d); console.log(all);
We create an object of 7 elements by using Symbol.iterator and generator functions. In the second part, we assign our object to a constant all. At the end, we print its value.
翻譯小心得| 這個段落的非同步(異步)asynchronous(Async)概念比較複雜,翻譯同時需要延伸閱讀其他參考資料,才能比較了解內容。摘要: (1)Promise物件裡面包含一個完成或失敗的非同步操作,以及執行產生的值。 (2)使用2個參數,分別是resolve和reject,會回傳其中之一。 (3)Promise語法專門用來處理非同步的執行。 迭代器和生成器還有待研究...... >< Finally, the article above is from SOLOLEARN . I translated it just for practice, personal use only. If that is inappropriate, please contact me.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.