Sending Data into/out of a Generator

So we can get data out of a generator by using the yield keyword. We can also send data back_into_the generator, too. We do this using the.next()method:

function* displayResponse() {
    const response = yield;
    console.log(`Your response is "${response}"!`);
}

const iterator = displayResponse();

iterator.next(); // starts running the generator function
iterator.next('Hello Udacity Student'); // send data into the generator
// the line above logs to the console: Your response is "Hello Udacity Student"!

Calling.next()with data (i.e..next('Richard')) will send data into the generator function where it last left off. It will "replace" the yield keyword with the data that you provided.

데이터가있는 .next ()를 호출하면 (즉, .next ( 'Richard')) 데이터가 마지막으로 중단된 생성기 함수로 데이터가 전송됩니다. yield 키워드를 제공한 데이터로 "대체"합니다.

따라서 yield 키워드는 생성기를 일시 중지하는데 사용되며 생성기 외부로 데이터를 보내는데 사용됩니다. 그런 다음 .next () 메서드를 사용하여 데이터를 생성기로 전달합니다. 다음은 이 두 가지를 모두 사용하여 한 번에 하나씩 이름 목록을 순환하는 예제입니다.

So theyieldkeyword is used to pause a generator_and_used to send data outside of the generator, and then the.next()method is used to pass data_into_the generator. Here's an example that makes use of both of these to cycle through a list of names one at a time:

function* getEmployee() {
    const names = ['Amanda', 'Diego', 'Farrin', 'James', 'Kagure', 'Kavita', 'Orit', 'Richard'];
    const facts = [];

    for (const name of names) {
        // yield *out* each name AND store the returned data into the facts array
        facts.push(yield name); 
    }

    return facts;
}

const generatorIterator = getEmployee();

// get the first name out of the generator
let name = generatorIterator.next().value;

// pass data in *and* get the next name
name = generatorIterator.next(`${name} is cool!`).value; 

// pass data in *and* get the next name
name = generatorIterator.next(`${name} is awesome!`).value; 

// pass data in *and* get the next name
name = generatorIterator.next(`${name} is stupendous!`).value; 

// you get the idea
name = generatorIterator.next(`${name} is rad!`).value; 
name = generatorIterator.next(`${name} is impressive!`).value;
name = generatorIterator.next(`${name} is stunning!`).value;
name = generatorIterator.next(`${name} is awe-inspiring!`).value;

// pass the last data in, generator ends and returns the array
const positions = generatorIterator.next(`${name} is magnificent!`).value; 

// displays each name with description on its own line
positions.join('\n');

QUIZ QUESTION

What will happen if the following code is run?

function* createSundae() {
    const toppings = [];

    toppings.push(yield);
    toppings.push(yield);
    toppings.push(yield);

    return toppings;
}

var it = createSundae();
it.next('hot fudge');
it.next('sprinkles');
it.next('whipped cream');
it.next();
  • Thetoppingsarray will haveundefinedas its last item

  • An error will occur

  • The generator will be paused, waiting for it's last call to.next()

SUBMIT: Because the first call to .next() passes in some data. But that data doesn't get stored anywhere. The last call to .next() should have some data since it's being yielded into the last call to toppings.push().

Generators are a powerful new kind of function that is able to pause its execution while also maintaining its own state. Generators are great for iterating over a list of items one at a time so you can handle each item on its own before moving on to the next one. You can also use generators to handle nested callbacks. For example, let's say that an app needs to get a list of all repositories_and_the number of times they've been starred. Well, before you can get the number of stars for each repository, you'd need to get the user's information. Then after retrieving the user's profile the code can then take that information to find all of the repositories.

Generators will also be used heavily in upcoming additions to the JavaScript language. One upcoming feature that will make use of them is async functions.

generator는 자체 상태를 유지하면서 실행을 일시 중지 할 수 있는 강력한 새 기능입니다. generator는 한 번에 하나씩 항목 목록을 반복하는데 유용하므로 각 항목을 독자적으로 처리하여 다음 항목으로 넘어갈 수 있습니다. generator를 사용하여 nested callbacks(중첩 콜백)을 처리 할 수도 있습니다. 예를 들어 앱에 모든 저장소와 별표가 표시된 횟수의 목록을 가져와야한다고 가정해보겠습니다. 각 repositories에 대한 별의 수를 얻기 전에 사용자의 정보를 얻어야합니다. 그런 다음 사용자의 프로필을 검색한 후 코드는 해당 정보를 가져와 모든 repositories를 찾습니다.

generator는 또한 곧 추가될 JavaScript 언어에 많이 사용될 것입니다. 그(것)들을 사용할 다가오는 특징은 비동기 기능입니다.

results matching ""

    No results matching ""