Scholarpeak

Understanding Async/Await

Master the async/await pattern essential for Web3 development.

What is Async?

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.

typescript
// Regular function
function greet(name) {
  return 'Hello ' + name;
}

// Async function (always returns a Promise)
async function greetAsync(name) {
  return 'Hello ' + name;
}

What is Await?

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 (❌):

typescript
const result = fetchData();  // Returns a Promise immediately
console.log(result);  // Logs Promise { <pending> }

With await (✓):

typescript
const result = await fetchData();  // Waits for Promise to resolve
console.log(result);  // Logs the actual data

Real-Life Analogy

Think of ordering food at a restaurant:

Without await

You order food, then immediately try to eat. But the food isn&apos;t ready yet!

With await

You order food, then wait for it to be prepared. Once it&apos;s ready, you eat.

Web3 Example: Getting Balance

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.

typescript
// 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..."
}

What is a Promise?

A Promise is a JavaScript object that represents a value that may not be available yet. It can be in one of three states:

Pending

The operation hasn&apos;t completed yet

Fulfilled

The operation completed successfully

Rejected

The operation failed with an error

Error Handling with Try/Catch

When using await, wrap your code in a try/catch block to handle errors gracefully.

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

Common Mistakes

Forgetting async keyword

typescript
// ❌ Will throw error
function test() {
  const data = await fetchData();  // Can't use await outside async function
}
typescript
// ✅ Correct
async function test() {
  const data = await fetchData();
}

Not awaiting a promise

typescript
// ❌ balance is a Promise
const balance = getBalance(address);
console.log(balance.toFixed(2));  // Error!
typescript
// ✅ Wait for the balance
const balance = await getBalance(address);
console.log(balance.toFixed(2));  // Works!

Key Takeaways

  • ✓ Use async to declare asynchronous functions
  • ✓ Use await to pause and wait for Promises
  • ✓ Always wrap await calls in try/catch blocks
  • ✓ Web3 operations are asynchronous because they involve network requests
  • ✓ Without await, you get a pending Promise instead of the actual data