Skip to contentPlayForge

What is a Promise in JavaScript?

Written by Jatin Thacker, Automation Architect · Updated

A Promise is an object standing in for the result of work that has not finished yet, such as a page load or reading text from an element. It starts pending, then becomes either fulfilled with a value or rejected with an error, and await waits for that to happen.

This answer is one piece of Chapter 6: Async and Await.

  • Error Handling & Debugging
  • Callbacks & Promises
  • Async/Await Mastery
  • Practice and interview questions: Asynchronous JavaScript & Modern ES6+

Almost every Playwright call has to wait for the browser, so none of them can hand back an answer straight away. Each one returns a Promise instead: a placeholder for the answer that will arrive later.

A Promise has three states. It starts pending. If the work succeeds, it becomes fulfilled and holds the value. If the work fails, it becomes rejected and holds the error. Once it is fulfilled or rejected it is settled and never changes again.

The example proves that page actions return Promises. page.goto() is called without await and stored in navigation, and navigation instanceof Promise prints true. The same holds for price.textContent(): the variable pending holds a Promise, not the text. Only await pending gives the real value, ₹11,900.

This is why a missing await is so damaging. Without it, your variable holds the Promise and the test moves on before the browser has answered. The example ends with a web-first assertion, toHaveText('₹11,900'), because that is the right way to check the text: it retries until the price matches.

promise.spec.js(https://practice.learnplayforge.com)
import { test, expect } from '@playwright/test'; test('page actions return promises', async ({ page }) => { const navigation = page.goto('/catalog.html?mock=static&seed=42&autologin=1'); console.log('goto returned a Promise:', navigation instanceof Promise); await navigation; const price = page.locator('article[data-sku="MRD-1003"]').getByTestId('product-price'); const pending = price.textContent(); console.log('textContent returned a Promise:', pending instanceof Promise); console.log('after await:', await pending); await expect(price).toHaveText('₹11,900'); });
Output
goto returned a Promise: true
textContent returned a Promise: true
after await: ₹11,900

  1 passed (2.6s)
Source:Promise, await
Test yourself
A test runs const label = page.getByTestId('cart-total').textContent() with no await. What does label hold?

Practised in the full course: the drill A promise is not a user.

See the chapter

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.