0

[Playwright Interview question #25]: Tại sao sử dụng async & await trong Playwright?

Câu hỏi phỏng vấn #25: Why we use async & await in Playwright?

Trả lời mẫu:

1. Asynchronous Nature của Browser Automation:

// Browser operations take time
// ❌ Wrong - không chờ completion
page.goto('https://example.com');
page.click('#button'); // Fails - page chưa load

// ✅ Correct - chờ operations complete
await page.goto('https://example.com');
await page.click('#button');

2. Promise-based API:

// Playwright methods return Promises
const response = page.goto('/'); // Returns Promise<Response>

// Must await to get actual value
const response = await page.goto('/');
console.log(response.status()); // 200

3. Sequential Execution:

async function loginUser() {
  await page.goto('/login');
  await page.fill('#username', 'user@test.com');
  await page.fill('#password', 'password123');
  await page.click('#submit');
  await expect(page).toHaveURL('/dashboard');
}

4. Error Handling:

try {
  await page.click('#non-existent');
} catch (error) {
  console.log('Element not found:', error.message);
}

5. Parallel Operations:

// Run operations in parallel
const [response, download] = await Promise.all([
  page.waitForResponse('**/api/data'),
  page.click('#download-btn')
]);

6. Clean, Readable Code:

// Async/await makes code look synchronous
async function testCheckout() {
  await addProductToCart();
  await goToCheckout();
  await fillShippingInfo();
  await submitOrder();
  await verifyOrderSuccess();
}

💡 Tips:

  • Always use async/await với Playwright methods
  • Don't forget await - common source of bugs
  • Use Promise.all() cho parallel operations
  • async/await better than .then() chains

Lời Kết

Playwright đang trở thành một trong những automation frameworks phổ biến nhất cho web testing. Thông qua series này, hy vọng bạn sẽ:

  • Nắm vững kiến thức từ cơ bản đến nâng cao
  • Tự tin trong các buổi phỏng vấn
  • Áp dụng hiệu quả vào dự án thực tế
  • Trở thành một phần của cộng đồng Playwright Việt Nam năng động

📚 Bắt đầu hành trình của bạn với: Bài 1: Playwright vs Selenium

💬 Có câu hỏi? Tham gia group Facebook của chúng mình!

Theo dõi series để không bỏ lỡ bài viết mới!


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí