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

Compare Async/Await and Generators...

Câu trả lời

When comparing async/await and generators in JavaScript to achieve similar functionality, particularly in handling asynchronous operations, it's essential to understand their distinct characteristics, strengths, and appropriate use cases.

Async/Await

Definition and Usage:
Async/await is a syntactic feature in JavaScript that allows you to write asynchronous code that looks and behaves like synchronous code. Introduced in ES2017, it is built on top of Promises and is designed to simplify the handling of asynchronous operations such as API calls, file I/O, etc.

Key Features:

  • Simplicity: Async/await makes asynchronous code easier to write and read. The syntax is clean and avoids the "callback hell" scenario.
  • Error Handling: Async functions use try/catch blocks for error handling, which is familiar to developers and similar to synchronous code error handling.
  • Single Value Return: An async function returns a single Promise that resolves to a single value.

Example:

javascript Copy
async function fetchData() {
    try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

Generators

Definition and Usage:
Generators are functions that can be exited and later re-entered, with their context (variable bindings) saved across re-entrances. They are marked by the function* syntax and use the yield keyword.

Key Features:

  • Iteration Control: Generators are particularly powerful for managing flow control in scenarios where operations need to pause and resume, such as iterating over a sequence of asynchronous actions.
  • Multiple Values: They can yield multiple values over time, each time they are resumed, making them suitable for handling streams of data.
  • Use with Promises: When combined with Promises, generators can handle asynchronous flows in a manner that can be more flexible than async/await.

Example:

javascript Copy
function* fetchSequentialData(urls) {
    for (const url of urls) {
        const response = yield fetch(url);
        const data = yield response.json();
        console.log(data);
    }
}

const generator = fetchSequentialData(['https://api.example.com/data1', 'https://api.example.com/data2']);

function handleYield(yielded) {
    if (!yielded.done) {
        yielded.value.then(result => handleYield(generator.next(result)));
    }
}

handleYield(generator.next());

Comparison

  • Complexity: Async/await is generally simpler to implement and ...
expert

expert

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

expert

In JavaScript, why is the this operator inconsistent?

junior

Explain the same-origin policy with regards to JavaScript.

junior

What is strict mode in javascript?

Bình luận

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

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