Câu hỏi phỏng vấn Javascript
Câu hỏi

What is the difference between the a...

Câu trả lời

The await and yield keywords in JavaScript are both used in the context of asynchronous programming but serve different purposes and operate within different contexts.

Await Keyword

The await keyword is used within asynchronous functions to pause the execution of the function until a Promise is resolved or rejected. It is used to handle asynchronous operations in a way that allows them to appear as though they are synchronous, making the code easier to read and understand. The await keyword can only be used inside an async function, which is marked by the async keyword before the function declaration. This keyword helps in managing asynchronous operations such as API calls, file operations, etc., where the execution needs to wait for a response before continuing.

Here's a basic example of how await is used:

javascript Copy
async function fetchData() {
    let data = await fetch('https://api.example.com/data');
    console.log(data);
}

In this example, the function execution pauses at the await line until the fetch operation completes. Once the Promise returned by fetch is settled, the function continues with the resolved value[1][2][6].

Yield Keyword

On the other hand, the yield keyword is used with generator functions, which are defined by the function* syntax. Generator functions are special because they can be paused and resumed, allowing them to produce a sequence of results over time, each time they are resumed. The yield keyword pauses the generator function and returns a value to the caller. It effectively makes the function execution stop at the point of yield and resumes from there the next time the generator's next() method is called.

Here's a simple example of a generator function using yield:

javascript Copy
function* idGenerator() {
    let id = 0;
    while(true) {
        yield id++;
    }
}

const gen = idGenerator();
console.log(gen.next().value); ...
expert

expert

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between a shim and a polyfill?

middle

When should I use Arrow Functions in ES6?

expert

Is JavaScript a pass-by-reference or pass-by-value language?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào