Nota: Saya telah menerangkan keseluruhan topik langkah demi langkah, tetapi jangan ragu untuk melangkau ke mana-mana bahagian yang anda mempunyai soalan atau memerlukan penjelasan.
Sebelum kita memasuki javascript tak segerak, penting untuk memahami apa itu javascript segerak dan sebab kita memerlukan cara tak segerak untuk menulis kod javascript, bukan?
Dalam pengaturcaraan segerak, tugasan dilaksanakan satu demi satu, secara berurutan. Tugasan seterusnya hanya boleh dimulakan selepas tugasan semasa selesai. Jika satu tugasan mengambil masa yang lama, yang lain mesti menunggu.
Anggap seperti menunggu dalam barisan di kedai runcit: jika orang di hadapan anda mempunyai banyak barang dan mengambil masa yang lama untuk menyemak, anda mesti menunggu giliran sehingga ia selesai sebelum anda boleh meneruskan.
console.log("Start cooking"); for (let i = 0; i < 5; i++) { console.log("Cooking dish " + (i + 1)); } console.log("Finish cooking");
Inilah yang berlaku:
Ia mencetak "Mulakan memasak".
Kemudian ia memasuki gelung dan mencetak setiap "Masak X" satu demi satu.
Hanya selepas gelung selesai, ia mencetak "Selesai memasak".
Dalam kes ini, kod berjalan dengan teratur, dan tiada perkara lain yang boleh berlaku sehingga tugas semasa (memasak setiap hidangan) selesai. Bayangkan jika satu hidangan mengambil masa 10 minit untuk dimasak—semua yang lain perlu menunggu sehingga hidangan itu habis.
Dalam pengaturcaraan tak segerak, tugasan boleh dimulakan dan semasa tugasan itu masih berjalan (cth., menunggu data daripada pelayan), tugasan lain boleh terus dijalankan. Anda tidak perlu menunggu satu tugasan selesai sebelum memulakan tugasan yang lain.
Fikirkan ia seperti membuat pesanan di restoran: anda memesan makanan anda dan semasa ia sedang disediakan, anda boleh terus bercakap dengan rakan anda atau menyemak telefon anda. Setelah makanan siap, pelayan akan membawakannya kepada anda.
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");
Inilah yang berlaku:
Ia mencetak "Mulakan memasak".
Fungsi setTimeout memulakan pemasa 3 saat. Tetapi daripada menunggu, JavaScript segera beralih ke baris seterusnya.
Ia mencetak "Sediakan perkara lain sementara menunggu".
Selepas 3 saat, pemasa selesai dan mencetak "Memasak sudah selesai!".
Terdapat tiga cara utama untuk menulis JavaScript tak segerak, dan ia adalah:
Panggil balik
Janji
Async/Tunggu
Ini ialah pendekatan utama untuk mengendalikan kod tak segerak dalam JavaScript.
Satu fungsi panggil balik dalam JavaScript ialah fungsi yang anda hantar sebagai hujah kepada fungsi lain. Idea asas ialah anda menghantar atau mentakrifkan fungsi sebagai hujah kepada fungsi lain, dan fungsi yang diluluskan itu dipanggil 'Fungsi Panggilan Balik'. Panggilan balik dipanggil (atau "dipanggil") selepas tugasan tertentu selesai, selalunya selepas tugas tak segerak, seperti mengambil data daripada pelayan.
Ini membolehkan fungsi utama anda terus melakukan perkara lain tanpa menunggu tugasan selesai. Apabila tugasan selesai, panggilan balik dicetuskan untuk mengendalikan keputusan.
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)
Kod ini menunjukkan konsep panggil balik dalam JavaScript. Begini caranya:
mainFunc mengambil fungsi panggil balik sebagai hujah.
Di dalam mainFunc, panggilan balik dilaksanakan serta-merta, tetapi memandangkan panggilan balik itu sendiri (fungsi cb) mengandungi setTimeout, ia menjadualkan console.log untuk dijalankan selepas 3 saat.
Sementara itu, mainFunc terus melaksanakan, mencetak mesej sebelum dan selepas memanggil panggilan balik.
Selepas 3 saat, setTimeout dalam panggilan balik selesai dan mesej tertunda dicetak.
Ini menunjukkan cara fungsi utama meneruskan tugasnya tanpa menunggu operasi tak segerak (kelewatan 3 saat dalam panggilan balik) selesai.
Neraka panggilan balik merujuk kepada situasi dalam JavaScript di mana berbilang panggilan balik bersarang antara satu sama lain dengan cara yang tidak terurus, menjadikan kod sukar dibaca, diselenggara dan nyahpepijat. Ia selalunya kelihatan seperti piramid fungsi bersarang, di mana setiap operasi tak segerak bergantung pada penyiapan operasi sebelumnya, yang membawa kepada panggilan balik bersarang dalam.
Neraka panggilan balik biasanya berlaku apabila anda mempunyai berbilang tugas tak segerak yang perlu dilakukan mengikut urutan, dan setiap tugasan bergantung pada hasil tugasan sebelumnya. Apabila lebih banyak tugasan ditambahkan, kod tersebut menjadi semakin inden dan sukar untuk diikuti, mengakibatkan struktur yang tidak kemas dan kompleks.
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.
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.
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) });
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));
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 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. |
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!" });
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() 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); });
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) });
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!" });
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 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.
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.
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.
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.
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.
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.
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.
Atas ialah kandungan terperinci JavaScript Asynchronous - Bersihkan Kekeliruan. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!