Master the async/await pattern essential for Web3 development.
async is a keyword that declares an asynchronous function. These functions always return a Promise, which is a placeholder for a value that may not be available yet but will be resolved in the future.
// Regular function
function greet(name) {
return 'Hello ' + name;
}
// Async function (always returns a Promise)
async function greetAsync(name) {
return 'Hello ' + name;
}await is a keyword that pauses the execution of an async function until a Promise is resolved. It can only be used inside an async function.
Without await (❌):
const result = fetchData(); // Returns a Promise immediately
console.log(result); // Logs Promise { <pending> }With await (✓):
const result = await fetchData(); // Waits for Promise to resolve
console.log(result); // Logs the actual dataThink of ordering food at a restaurant:
You order food, then immediately try to eat. But the food isn't ready yet!
You order food, then wait for it to be prepared. Once it's ready, you eat.
When you request an account's balance from Ethereum, it takes time to get the response from the network. That's why we use async/await.
// Without async/await - DOESN'T WORK
function getBalance(address) {
const balance = window.ethereum.request({
method: 'eth_getBalance',
params: [address, 'latest']
});
console.log(balance); // Logs Promise { <pending> }
}
// With async/await - WORKS!
async function getBalance(address) {
const balance = await window.ethereum.request({
method: 'eth_getBalance',
params: [address, 'latest']
});
console.log(balance); // Logs actual balance like "0x1234..."
}A Promise is a JavaScript object that represents a value that may not be available yet. It can be in one of three states:
The operation hasn't completed yet
The operation completed successfully
The operation failed with an error
When using await, wrap your code in a try/catch block to handle errors gracefully.
async function connectWallet() {
try {
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
console.log('Connected:', accounts[0]);
} catch (error) {
console.error('Failed to connect:', error.message);
}
}Pro Tip: Always wrap blockchain operations in try/catch because they can fail due to network issues, user rejection, or invalid parameters.
// ❌ Will throw error
function test() {
const data = await fetchData(); // Can't use await outside async function
}// ✅ Correct
async function test() {
const data = await fetchData();
}// ❌ balance is a Promise
const balance = getBalance(address);
console.log(balance.toFixed(2)); // Error!// ✅ Wait for the balance
const balance = await getBalance(address);
console.log(balance.toFixed(2)); // Works!async to declare asynchronous functionsawait to pause and wait for Promisestry/catch blocks