Look at this JavaScript code using async and await. What will it print?
async function fetchData() { return 'data loaded'; } async function main() { const result = await fetchData(); console.log(result); } main();
Remember that await pauses until the promise resolves and returns the resolved value.
The fetchData function returns a promise that resolves to 'data loaded'. Using await inside main waits for that promise to resolve and assigns the resolved value to result. So, console.log(result) prints 'data loaded'.
What will this code print?
async function fetchData() { return 'hello'; } async function main() { const result = fetchData(); console.log(result); } main();
Without await, the function returns a promise immediately.
The fetchData function is async and returns a promise. Without await, result is the promise itself, not its resolved value. So, console.log(result) prints the promise object.
Which of these best explains why async and await are needed in JavaScript?
Think about how async/await helps with code readability and flow.
async and await let us write asynchronous code that looks like normal synchronous code. This makes it easier to understand and maintain, especially when dealing with operations like fetching data or waiting for timers.
What will this code print, and in what order?
console.log('Start'); async function task() { console.log('Inside async'); return 'Done'; } task().then(result => console.log(result)); console.log('End');
Remember that the body of an async function runs immediately until the first await or return.
console.log('Start') runs first. Then task() is called, which immediately logs 'Inside async'. The function returns a resolved promise with 'Done'. Meanwhile, console.log('End') runs. Finally, the then callback logs 'Done'. So the order is Start, Inside async, End, Done.
Which statement best describes the main problem that async and await solve compared to traditional callbacks?
Think about how callback nesting can get complicated.
Callbacks often lead to deeply nested code called 'callback hell'. async and await let us write asynchronous code in a flat, readable style, avoiding this problem. They still use promises under the hood and do not block the main thread.