搜尋
首頁web前端js教程非同步 JavaScript - 消除混亂

Asynchronous JavaScript - Get Confusions Cleared

Hinweis: Ich habe das gesamte Thema Schritt für Schritt erklärt, Sie können aber jederzeit zu jedem Abschnitt springen, in dem Sie eine Frage haben oder einer Klärung bedürfen.

Bevor wir uns mit asynchronem Javascript befassen, ist es wichtig zu verstehen, was synchrones Javascript ist und warum wir eine asynchrone Methode zum Schreiben von Javascript-Code benötigen, oder?

Was ist synchrones JavaScript?

Bei der synchronen Programmierung werden Aufgaben nacheinander und sequentiell ausgeführt. Die nächste Aufgabe kann erst gestartet werden, nachdem die aktuelle Aufgabe abgeschlossen ist. Wenn eine Aufgabe lange dauert, muss alles andere warten.

Stellen Sie sich das vor, als würden Sie in einem Lebensmittelgeschäft in der Schlange stehen: Wenn die Person vor Ihnen viele Artikel hat und lange zum Auschecken braucht, müssen Sie warten, bis sie an der Reihe sind bevor Sie fortfahren können.

console.log("Start cooking");

for (let i = 0; i 



<p>Das passiert:</p>

<ol>
<li><p>Es wird „Kochen beginnen“ angezeigt.</p></li>
<li><p>Dann tritt es in eine Schleife ein und druckt nacheinander jedes „Kochgericht X“ aus.</p></li>
<li><p>Erst nachdem die Schleife abgeschlossen ist, wird „Fertig kochen“ gedruckt.</p></li>
</ol>

<p>In diesem Fall wird der Code der Reihe nach ausgeführt und nichts anderes kann passieren, bis die aktuelle Aufgabe (das Kochen jedes Gerichts) abgeschlossen ist. Stellen Sie sich vor, die Zubereitung eines Gerichts würde 10 Minuten dauern – alles andere müsste warten, bis dieses Gericht fertig ist.</p>

<h2>
  
  
  Was ist asynchrones JavaScript?
</h2>

<p>Bei der asynchronen Programmierung können Aufgaben gestartet werden, und während sie noch ausgeführt werden (z. B. beim Warten auf Daten von einem Server), können andere Aufgaben weiter ausgeführt werden. Sie müssen nicht warten, bis eine Aufgabe abgeschlossen ist, bevor Sie mit der nächsten beginnen.</p>

<p><strong>Stellen Sie es sich vor, als würden Sie eine Bestellung in einem Restaurant aufgeben</strong>: Sie bestellen Ihr Essen und während es zubereitet wird, können Sie weiter mit Ihren Freunden sprechen oder Ihr Telefon überprüfen. Sobald das Essen fertig ist, bringt es der Kellner zu Ihnen.</p>

<h4>
  
  
  Beispiel für asynchronen Code:
</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");

Das passiert:

  1. Es wird „Kochen beginnen“ angezeigt.

  2. Die setTimeout-Funktion startet einen 3-Sekunden-Timer. Aber anstatt zu warten, geht JavaScript sofort zur nächsten Zeile über.

  3. Es wird „Bereiten Sie andere Dinge vor, während Sie warten“ gedruckt.

  4. Nach 3 Sekunden läuft der Timer ab und gibt „Kochen ist fertig!“ aus.


Es gibt drei Hauptmethoden, um asynchrones JavaScript zu schreiben:

  1. Rückrufe

  2. Versprechen

  3. Asynchron/Warten

Dies sind die primären Ansätze für den Umgang mit asynchronem Code in JavaScript.

Rückrufe

Eine Callback-Funktion in JavaScript ist eine Funktion, die Sie als Argument an eine andere Funktion übergeben. Die Grundidee besteht darin, dass Sie eine Funktion als Argument an eine andere Funktion übergeben oder definieren und diese übergebene Funktion als „Callback-Funktion“ bezeichnet wird. Der Rückruf wird aufgerufen (oder „aufgerufen“), nachdem eine bestimmte Aufgabe abgeschlossen ist, oft nach einer asynchronen Aufgabe, wie dem Abrufen von Daten von einem Server.

Dadurch kann Ihre Hauptfunktion weiterhin andere Dinge tun, ohne auf den Abschluss der Aufgabe warten zu müssen. Wenn die Aufgabe erledigt ist, wird der Rückruf ausgelöst, um das Ergebnis zu verarbeiten.

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)

Dieser Code demonstriert das Callback-Konzept in JavaScript. So funktioniert es:

  1. mainFunc nimmt eine Callback-Funktion als Argument.

  2. Innerhalb von mainFunc wird der Callback sofort ausgeführt, aber da der Callback selbst (die cb-Funktion) ein setTimeout enthält, plant er die Ausführung von console.log danach 3 Sekunden.

  3. Währenddessen fährt mainFunc mit der Ausführung fort und druckt Nachrichten vor und nach dem Aufruf des Rückrufs.

  4. Nach 3 Sekunden ist setTimeout im Rückruf beendet und die verzögerte Nachricht wird gedruckt.

Dies zeigt, wie die Hauptfunktion ihre Aufgaben fortsetzt, ohne auf den Abschluss des asynchronen Vorgangs (die 3-Sekunden-Verzögerung im Rückruf) zu warten.

Was ist eine Callback-Hölle und wann passiert sie?

Callback-Hölle bezieht sich auf eine Situation in JavaScript, in der mehrere Callbacks auf unüberschaubare Weise ineinander verschachtelt sind, was das Lesen, Warten und Debuggen des Codes erschwert. Es sieht oft wie eine Pyramide verschachtelter Funktionen aus, bei der jede asynchrone Operation auf der Fertigstellung der vorherigen Operation beruht, was zu tief verschachtelten Rückrufen führt.

Die Callback-Hölle tritt normalerweise auf, wenn mehrere asynchrone Aufgaben nacheinander ausgeführt werden müssen und jede Aufgabe vom Ergebnis der vorherigen abhängt. Wenn weitere Aufgaben hinzugefügt werden, wird der Code zunehmend eingerückt und schwieriger zu befolgen, was zu einer unordentlichen und komplexen Struktur führt.

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:

  1. Promises – which flatten the code and make it more readable.

  2. 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:

  1. async function: Since fetchData function is marked as async, that means it returns a promise.

  2. 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.

  3. try/catch: We use a try/catch block to handle any potential errors during the async operation.

  4. 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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在JavaScript中替換字符串字符在JavaScript中替換字符串字符Mar 11, 2025 am 12:07 AM

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

自定義Google搜索API設置教程自定義Google搜索API設置教程Mar 04, 2025 am 01:06 AM

本教程向您展示瞭如何將自定義的Google搜索API集成到您的博客或網站中,提供了比標準WordPress主題搜索功能更精緻的搜索體驗。 令人驚訝的是簡單!您將能夠將搜索限制為Y

示例顏色json文件示例顏色json文件Mar 03, 2025 am 12:35 AM

本文系列在2017年中期進行了最新信息和新示例。 在此JSON示例中,我們將研究如何使用JSON格式將簡單值存儲在文件中。 使用鍵值對符號,我們可以存儲任何類型的

10個jQuery語法熒光筆10個jQuery語法熒光筆Mar 02, 2025 am 12:32 AM

增強您的代碼演示文稿:10個語法熒光筆針對開發人員在您的網站或博客上共享代碼段的開發人員是開發人員的常見實踐。 選擇合適的語法熒光筆可以顯著提高可讀性和視覺吸引力。 t

構建您自己的Ajax Web應用程序構建您自己的Ajax Web應用程序Mar 09, 2025 am 12:11 AM

因此,在這裡,您準備好了解所有稱為Ajax的東西。但是,到底是什麼? AJAX一詞是指用於創建動態,交互式Web內容的一系列寬鬆的技術。 Ajax一詞,最初由Jesse J創造

8令人驚嘆的jQuery頁面佈局插件8令人驚嘆的jQuery頁面佈局插件Mar 06, 2025 am 12:48 AM

利用輕鬆的網頁佈局:8 ESTISSEL插件jQuery大大簡化了網頁佈局。 本文重點介紹了簡化該過程的八個功能強大的JQuery插件,對於手動網站創建特別有用

什麼是這個&#x27;在JavaScript?什麼是這個&#x27;在JavaScript?Mar 04, 2025 am 01:15 AM

核心要點 JavaScript 中的 this 通常指代“擁有”該方法的對象,但具體取決於函數的調用方式。 沒有當前對象時,this 指代全局對象。在 Web 瀏覽器中,它由 window 表示。 調用函數時,this 保持全局對象;但調用對象構造函數或其任何方法時,this 指代對象的實例。 可以使用 call()、apply() 和 bind() 等方法更改 this 的上下文。這些方法使用給定的 this 值和參數調用函數。 JavaScript 是一門優秀的編程語言。幾年前,這句話可

10 JavaScript和JQuery MVC教程10 JavaScript和JQuery MVC教程Mar 02, 2025 am 01:16 AM

本文介紹了關於JavaScript和JQuery模型視圖控制器(MVC)框架的10多個教程的精選選擇,非常適合在新的一年中提高您的網絡開發技能。 這些教程涵蓋了來自Foundatio的一系列主題

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!