目標:2021年2月起,每周一篇文章翻譯,從跟程式相關的短文/新聞開始,過程中也會接觸到程式專有名詞,能試著自己詮釋加強概念。4月起主題,從SOLOLEARN平台做JavaScript篇章的翻譯。

■□■ Oct, Week 4 ■□■ Title: JavaScript Author、Platform: SOLOLEARN Source: https://www.sololearn.com/learning/1024

ES6 Promises

ES6的Promise物件

Promise is a better way for asynchronous programming when compared to the common way of using a setTimeout() type of method.

Consider this example:

與一般使用setTimeout()的方式比較起來Promise物件是非同步(asynchronous)程式更好的處理方式。試想這個範例:

setTimeout(function() {
console.log("Work 1");
setTimeout(function() {
console.log("Work 2");
}, 1000);
}, 1000);
console.log("End");

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.

它依序印出END、Work1和Work2(非同步的完成作業),但如果有更多像這樣的事件,程式碼會變得非常複雜。

ES6 comes to the rescue in such situations. A promise can be created as follows:

在這種狀況下,ES6前來救援,promise可以被新增如下:

new Promise(function(resolve, reject) {
// Work
if (success)
resolve(result);
else
reject(Error("failure"));
});

Here, resolve is the method for success and reject is the method for failure.

這裡,resolve是成功執行的方法,而reject是失敗執行的方法。

If a method returns a promise, its calls should use the then method which takes two methods as input; one for success and the other for the failure.

For Example:

如果方法method回傳一個promise,它的呼叫應該使用then方法,它需要2個方法當作輸入值,一個在成功時執行,另一個在失敗時執行。例如

function asyncFunc(work) {
return new Promise(function(resolve, reject) {
if (work === "")
reject(Error("Nothing"));
setTimeout(function() {
resolve(work);
}, 1000);
});
}

asyncFunc("Work 1") // Task 1
.then(function(result) {
console.log(result);
return asyncFunc("Work 2"); // Task 2
}, function(error) {
console.log(error);
})
.then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
console.log("End");

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.

它也會印出END、Work1和Work2(非同步的完成作業),但很明顯地比前面的範例更容易閱讀,在更複雜的情況下,他更容易執行。

TIP:Run the code and see how it works!

提示:跑程式碼,看他如何運作。

-----

Iterators & Generators

迭代器和生成器

Symbol.iterator is the default iterator for an object. The for...of loops are based on this type of iterator.

Symbol.iterator是物件預設的迭代器,for...of 迴圈就是建立在這個類型的迭代器上。

In the example below, we will see how we should implement it and how generator functions are used.
Example:

在下方的範例中,我們將看到如何執行(implement)它以及生成器函式(generator functions)如何被使用,範例:

let myIterableObj = {
[Symbol.iterator] : function* () {
yield 1; yield 2; yield 3;
...
console.log([...myIterableObj]);

First, we create an object, and use the Symbol.iterator and generator function to fill it with some values.

首先,我們新增一個物件,然後使用Symbol.iterator和generator function去填入一些數值。

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.

我們稍後可以離開再重新進入產生器函式,他們的變數綁定(variable bindings /內容context)將被儲存在整個過程。他們在非同步程式(asynchronous)是非常有力的工具,尤其是當跟Promises結合的時候,它們也非常實用可以用來新增特殊需求的迴圈。

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:

我們可以在個別函式中巢狀組合產生器函式,新增更複雜的結構,當我們呼叫他們時傳遞變數。
下方的範例將展示一個實用的方式,看看我們可以如何同時使用generator functions和Symbol.iterators。
範例:

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.

我們用Symbol.iterator和generator functions 新增有7個元素的物件,在第二個部分,我們將物件賦予給常數all,最後,我們印出它的值。

TIP:Run the code and see how it works!

提示:跑程式碼,看他如何運作。

-----

翻譯小心得| 這個段落的非同步(異步)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.


This free site is ad-supported. Learn more