참고: 전체 주제를 단계별로 설명했지만 질문이 있거나 설명이 필요한 섹션으로 건너뛰셔도 됩니다.
비동기 자바스크립트를 시작하기 전에 동기 자바스크립트가 무엇인지, 자바스크립트 코드를 작성하기 위해 비동기 방식이 필요한 이유를 이해하는 것이 중요합니다. 그렇죠?
동기식 JavaScript란 무엇입니까?
동기식 프로그래밍에서는 작업이 순차적인 방식으로 하나씩 실행됩니다. 다음 작업은 현재 작업이 완료된 후에만 시작할 수 있습니다. 한 작업에 시간이 오래 걸리면 다른 작업은 모두 기다려야 합니다.
식료품점에서 줄을 서서 기다리는 것과 같다고 생각하세요: 앞에 있는 사람이 물건이 많아서 계산하는 데 시간이 오래 걸린다면, 물건이 끝날 때까지 차례를 기다려야 합니다. 진행하기 전에.
console.log("Start cooking"); for (let i = 0; i <p>상황은 다음과 같습니다.</p> <ol> <li><p>"요리 시작"이 인쇄됩니다.</p></li> <li><p>그런 다음 루프에 들어가 각 "요리 X"를 차례로 인쇄합니다.</p></li> <li><p>루프가 완료된 후에야 "요리 완료"가 인쇄됩니다.</p></li> </ol> <p>이 경우 코드는 순서대로 실행되며 현재 작업(각 요리 요리)이 완료될 때까지 아무 일도 일어나지 않습니다. 한 가지 요리를 요리하는 데 10분이 걸린다면 다른 모든 요리는 해당 요리가 끝날 때까지 기다려야 합니다.</p> <h2> 비동기 JavaScript란 무엇입니까? </h2> <p>비동기 프로그래밍에서는 작업을 시작할 수 있으며 작업이 계속 실행되는 동안(예: 서버에서 데이터를 기다리는 동안) 다른 작업을 계속 실행할 수 있습니다. 다른 작업을 시작하기 전에 한 작업이 완료될 때까지 기다릴 필요가 없습니다.</p> <p><strong>식당에서 주문하는 것과 같다</strong>: 음식을 주문하고 음식이 준비되는 동안 계속해서 친구들과 대화하거나 휴대폰을 확인할 수 있습니다. 음식이 준비되면 웨이터가 음식을 가져다줄 것입니다.</p> <h4> 비동기 코드의 예: </h4> <pre class="brush:php;toolbar:false">console.log("Start cooking"); setTimeout(() => { console.log("Cooking is done!"); }, 3000); // Simulate a task that takes 3 seconds console.log("Prepare other things while waiting");
상황은 다음과 같습니다.
"요리 시작"이 인쇄됩니다.
setTimeout 함수는 3초 타이머를 시작합니다. 하지만 JavaScript는 기다리지 않고 즉시 다음 줄로 이동합니다.
'기다리는 동안 다른 것들을 준비하세요'라고 출력됩니다.
3초 후 타이머가 완료되고 "요리 완료!"가 인쇄됩니다.
비동기 JavaScript를 작성하는 세 가지 주요 방법은 다음과 같습니다.
콜백
약속
비동기/대기
이는 JavaScript에서 비동기 코드를 처리하는 기본 접근 방식입니다.
콜백
JavaScript의 콜백 함수는 다른 함수에 인수로 전달하는 함수입니다. 기본 아이디어는 함수를 다른 함수의 인수로 전달하거나 정의하고, 전달된 함수를 '콜백 함수'라고 합니다. 콜백은 특정 작업이 완료된 후, 종종 서버에서 데이터를 가져오는 것과 같은 비동기 작업 후에 호출됩니다.
이렇게 하면 작업이 완료될 때까지 기다리지 않고 기본 기능이 다른 작업을 계속할 수 있습니다. 작업이 완료되면 콜백이 트리거되어 결과를 처리합니다.
function mainFunc(callback){ console.log("this is set before setTimeout") callback() console.log("this is set after setTimeout") } function cb(){ setTimeout(()=>{ console.log("This is supposed to be painted after 3 second") },3000) } mainFunc(cb)
이 코드는 JavaScript의 콜백 개념을 보여줍니다. 작동 방식은 다음과 같습니다.
mainFunc는 콜백 함수를 인수로 사용합니다.
mainFunc 내부에서는 콜백이 즉시 실행되지만 콜백 자체(cb 함수)에는 setTimeout이 포함되어 있으므로 이후에 실행되도록 console.log를 예약합니다. 3초.
그동안 mainFunc는 계속 실행되어 콜백 호출 전후에 메시지를 인쇄합니다.
3초 후 콜백 내부의 setTimeout이 완료되고 지연된 메시지가 출력됩니다.
이는 비동기 작업(콜백의 3초 지연)이 완료될 때까지 기다리지 않고 기본 함수가 작업을 계속하는 방법을 보여줍니다.
콜백 지옥이란 무엇이며 언제 발생합니까?
콜백 지옥은 여러 콜백이 관리하기 어려운 방식으로 서로 중첩되어 코드를 읽고 유지 관리하고 디버그하기 어렵게 만드는 JavaScript의 상황을 말합니다. 각 비동기 작업이 이전 작업의 완료에 의존하여 깊게 중첩된 콜백으로 이어지는 중첩된 함수의 피라미드처럼 보이는 경우가 많습니다.
콜백 지옥은 일반적으로 순차적으로 수행해야 하는 여러 비동기 작업이 있고 각 작업이 이전 작업의 결과에 따라 달라질 때 발생합니다. 작업이 추가될수록 코드가 점점 들여쓰기되고 따라가기가 어려워져 구조가 지저분해지고 복잡해집니다.
getData((data) => { processData(data, (processedData) => { saveData(processedData, (savedData) => { notifyUser(savedData, () => { console.log("All tasks complete!"); }); }); }); });
Here, each task is dependent on the previous one, leading to multiple levels of indentation and difficult-to-follow logic. If there’s an error at any point, handling it properly becomes even more complex.
To rescue you from callback hell, modern JavaScript provides solutions like:
Promises – which flatten the code and make it more readable.
Async/Await – which simplifies chaining asynchronous operations and makes the code look synchronous.
Promises
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its result. It’s like a promise you make in real life: something may not happen immediately, but you either fulfill it or fail to fulfill it.
In JavaScript, Promises allow you to write asynchronous code in a cleaner way, avoiding callback hell. A Promise is created using the new Promise syntax, and it takes a function (which is constructor function) with two parameters: resolve (if the task is successful) and reject (if it fails).
const myPromise = new Promise((resolve, reject) => { // Simulating an asynchronous task like fetching data const success = true; // Change to false to simulate failure setTimeout(() => { if (success) { resolve("Task completed successfully!"); // Success } else { reject("Task failed!"); // Failure } }, 2000); // 2-second delay });
Here:
The promise simulates a task that takes 2 seconds.
If the task is successful (success is true), it calls resolve with a message.
If it fails (success is false), it calls reject with an error message.
How to handle a Promise
To handle the result of a Promise, we use two methods:
.then() for a successful result (when the Promise is fulfilled).
.catch() for an error (when the Promise is rejected).
myPromise .then((message) => { console.log(message); // "Task completed successfully!" (if resolve was called) }) .catch((error) => { console.log(error); // "Task failed!" (if reject was called) });
Chaining in Promises
Promises allow you to chain asynchronous operations using the .then() method, which makes the code more linear and easier to follow. Each .then() represents a step in the asynchronous process. The .catch() method allows you to centralize error handling at the end of the promise chain, making it more organized.
fetchData() .then(data => processData1(data)) .then(result1 => processData2(result1)) .then(result2 => processData3(result2)) .catch(error => handleError(error));
Promises promote a more readable and maintainable code structure by avoiding deeply nested callbacks. The chaining and error-handling mechanisms contribute to a clearer and more organized codebase.
// Callback hell fetchData1(data1 => { processData1(data1, result1 => { fetchData2(result1, data2 => { processData2(data2, result2 => { fetchData3(result2, data3 => { processData3(data3, finalResult => { console.log("Final result:", finalResult); }); }); }); }); }); }); // Using Promises fetchData1() .then(result1 => processData1(result1)) .then(data2 => fetchData2(data2)) .then(result2 => processData2(result2)) .then(data3 => fetchData3(data3)) .then(finalResult => { console.log("Final result:", finalResult); }) .catch(error => handleError(error));
finally Method
The finally method is used to execute code, regardless of whether the Promise is resolved or rejected.
myPromise .then((data) => { console.log("Data:", data); }) .catch((error) => { console.error("Error:", error); }) .finally(() => { console.log("Finally block"); // This runs no matter what });
If the promise is fulfilled (i.e., it successfully gets data), the .then() method will be executed. On the other hand, if the promise encounters an error, the .catch() method will be called to handle the error. However, the .finally() method has no such condition—it will always be executed, regardless of whether the promise was resolved or rejected. Whether the .then() or .catch() is triggered, the .finally() block will definitely run at the end.
It's useful for cleaning up resources, stopping loading indicators, or doing something that must happen after the promise completes, regardless of its result.
JavaScript Promise Methods
JavaScript provides several Promise methods that make working with asynchronous tasks more flexible and powerful. These methods allow you to handle multiple promises, chain promises, or deal with various outcomes in different ways
Method | Description |
---|---|
all (iterable) | Waits for all promises to be resolved or any one to be rejected. |
allSettled (iterable) | Waits until all promises are either resolved or rejected. |
any (iterable) | Returns the promise value as soon as any one of the promises is fulfilled. |
race (iterable) | Waits until any of the promises is resolved or rejected. |
reject (reason) | Returns a new promise object that is rejected for the given reason. |
resolve (value) | Returns a new promise object that is resolved with the given value. |
Promise.all() - Parallel Execution
You can use Promise.all() to execute multiple asynchronous operations concurrently and handle their results collectively.
This method takes an array of promises and runs them in parallel which returns a new Promise. This new Promise fulfils with an array of resolved values when all the input Promises have fulfilled, or rejects with the reason of the first rejected Promise.
Copy code const promise1 = Promise.resolve(10); const promise2 = Promise.resolve(20); const promise3 = Promise.resolve(30); Promise.all([promise1, promise2, promise3]).then((values) => { console.log(values); // [10, 20, 30] });
If one of the promises rejects, the whole Promise.all() will reject:
const promise1 = Promise.resolve(10); const promise2 = Promise.reject("Error!"); Promise.all([promise1, promise2]) .then((values) => { console.log(values); }) .catch((error) => { console.log(error); // "Error!" });
Promise.allSettled()
This method takes an array of promises and returns a new promise after all of them finish their execution, whether they succeed or fail. Unlike Promise.all(), it doesn't fail if one promise fails. Instead, it waits for all the promises to complete and gives you an array of results that show if each one succeeded or failed.
It’s useful when you want to know the result of every promise, even if some fail.
const promise1 = Promise.resolve("Success!"); const promise2 = Promise.reject("Failure!"); Promise.allSettled([promise1, promise2]).then((results) => { console.log(results); // [{ status: 'fulfilled', value: 'Success!' }, { status: 'rejected', reason: 'Failure!' }] });
Promise.any()
Promise.any() takes an array of promises and returns a promise that resolves as soon as any one promise resolves. If all input Promises are rejected, then Promise.any() rejects with an AggregateError containing an array of rejection reasons.
It’s useful when you need just one successful result from multiple promises.
const promise1 = fetchData1(); const promise2 = fetchData2(); const promise3 = fetchData3(); Promise.any([promise1, promise2, promise3]) .then((firstFulfilledValue) => { console.log("First promise fulfilled with:", firstFulfilledValue); }) .catch((allRejectedReasons) => { console.error("All promises rejected with:", allRejectedReasons); });
Promise.race()
This method takes an array of promises and returns a new promise that resolves or rejects as soon as the first promise settles (either resolves or rejects).
It’s useful when you want the result of the fastest promise, ignoring the others.
const promise1 = new Promise((resolve) => setTimeout(resolve, 100, "First")); const promise2 = new Promise((resolve) => setTimeout(resolve, 200, "Second")); Promise.race([promise1, promise2]).then((value) => { console.log(value); // "First" (because promise1 resolves first) });
Promise.resolve()
This method immediately resolves a promise with a given value. It’s useful for creating a promise that you already know will be fulfilled.
const resolvedPromise = Promise.resolve("Resolved!"); resolvedPromise.then((value) => { console.log(value); // "Resolved!" });
Promise.reject()
This method immediately rejects a promise with a given error or reason. It’s useful for creating a promise that you know will fail.
const rejectedPromise = Promise.reject("Rejected!"); rejectedPromise.catch((error) => { console.log(error); // "Rejected!" });
I hope you have no confusion regarding promises after carefully reading this explanation of promises. Now, it’s time to move on Async/Await.
Async/Await
async / await is a modern way to handle asynchronous operations in JavaScript, introduced in ES2017 (ES8). It’s built on top of Promises but provides a cleaner and more readable syntax, making asynchronous code look and behave more like synchronous code. This makes it easier to understand and debug.
How async and await Work
When you declare a function with the async keyword, it always returns a Promise. Even if you don't explicitly return a promise, JavaScript wraps the return value inside a resolved promise.
The await keyword can only be used inside an async function. It makes JavaScript wait for the promise to resolve before moving on to the next line of code. It “pauses” the execution of the function, allowing you to handle asynchronous tasks more sequentially, just like synchronous code.
Let’s look at a simple example to see how this works:
async function fetchData() { try { const response = await fetch("https://api.example.com/data"); const data = await response.json(); console.log("Data:", data); } catch (error) { console.error("Error fetching data:", error); } finally { console.log("Fetch operation complete"); } } fetchData();
How it works:
async function: Since fetchData function is marked as async, that means it returns a promise.
await fetch(): The await pauses the execution of the function until the promise returned by fetch() resolves. It then continues with the next line after the promise is resolved.
try/catch: We use a try/catch block to handle any potential errors during the async operation.
finally: Regardless of success or failure, the finally block will execute.
Why Use async / await?
With async/await, your code becomes more readable and flows more naturally. This makes it easier to follow the logic, especially when dealing with multiple asynchronous operations.
Compare this to handling promises with .then():
fetch("https://api.example.com/data") .then(response => response.json()) .then(data => { console.log("Data:", data); }) .catch(error => { console.error("Error fetching data:", error); }) .finally(() => { console.log("Fetch operation complete"); });
The async/await version looks cleaner and easier to understand. async/await helps avoid the nesting of callbacks or .then() chains, making your code more linear and easier to follow.
Example with Multiple await
You can also handle multiple asynchronous tasks in a sequence without needing to chain promises.
async function processOrders() { const user = await getUserDetails(); // Waits for user details const orders = await getOrders(user.id); // Waits for orders console.log("Orders:", orders); } processOrders();
In this example, the function waits for each task to finish before moving on to the next, just like how synchronous code would behave.
Parallel Execution with Promise.all() and async/await
If you want to perform multiple asynchronous operations at the same time (in parallel), you can still use Promise.all() with async/await:
async function getAllData() { const [user, orders] = await Promise.all([getUserDetails(), getOrders()]); console.log("User:", user); console.log("Orders:", orders); }
Here, both getUserDetails() and getOrders() run simultaneously, and the function waits for both to finish before logging the results.
Conclusion
In JavaScript, handling asynchronous operations has evolved over time, offering different tools to make code more manageable and efficient. Callbacks were the first approach, but as the complexity of code grew, they often led to issues like "callback hell." Promises came next, providing a cleaner, more structured way to manage async tasks with .then() and .catch(), improving readability and reducing nesting.
Finally, async/await was introduced as a modern syntax built on promises, making asynchronous code look more like synchronous code. It simplifies the process even further, allowing for easier-to-read, more maintainable code. Each of these techniques plays an important role in JavaScript, and mastering them helps you write more efficient, clear, and robust code.
Understanding when to use each method—callbacks for simple tasks, promises for structured handling, and async/await for readable, scalable async code—will empower you to make the best choices for your projects.
My Last Words
I used to get confused by the concept of promises, especially the different methods of promises. Callbacks were a big challenge for me because the syntax always seemed very confusing. So, I read various sources online, including chatbots, to come up with this description. To be honest, chatbots don’t always provide a straight and understandable answer. So, I didn’t just copy and paste from different places—I simplified everything so that it can serve as a clear note for me and for anyone else who has difficulty grasping these concepts. I hope this note leaves you with zero confusion.
以上是异步 JavaScript - 消除混乱的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

不同JavaScript引擎在解析和执行JavaScript代码时,效果会有所不同,因为每个引擎的实现原理和优化策略各有差异。1.词法分析:将源码转换为词法单元。2.语法分析:生成抽象语法树。3.优化和编译:通过JIT编译器生成机器码。4.执行:运行机器码。V8引擎通过即时编译和隐藏类优化,SpiderMonkey使用类型推断系统,导致在相同代码上的性能表现不同。

JavaScript在现实世界中的应用包括服务器端编程、移动应用开发和物联网控制:1.通过Node.js实现服务器端编程,适用于高并发请求处理。2.通过ReactNative进行移动应用开发,支持跨平台部署。3.通过Johnny-Five库用于物联网设备控制,适用于硬件交互。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

Dreamweaver Mac版
视觉化网页开发工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3汉化版
中文版,非常好用

WebStorm Mac版
好用的JavaScript开发工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。