Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Chaining Promises for Sequential Asynchronous Tasks

Tech 1

The then() method of a Promise returns a new Promise, enabling you to connect multiple asynchronous operations without deeply nested callbacks. What ever you return in side a then() callback determines the state and result of the subsequent Promise in the chain.

The first example uses setTimeout to mock network requests and demonstrates how chaining works in practice.

function fetchProvince() {
  return new Promise((resolve) => {
    setTimeout(() => resolve('Guangdong'), 1000);
  });
}

const provincePromise = fetchProvince();

const cityPromise = provincePromise.then((province) => {
  console.log('Province:', province);
  return new Promise((resolve) => {
    setTimeout(() => resolve(`${province} - Shenzhen`), 1000);
  });
});

cityPromise.then((result) => {
  console.log('City:', result);
});

console.log('Are the promises identical?', provincePromise === cityPromise); // false

The second example shows how Promise chaining replaces callback hell when fetching hierarchical data. Using the fetch API, it loads a list of provinces, then cities for the first province, and finally districts for the first city, updating a dropdown at each step.

let selectedProvince;
fetch('/api/province')
  .then(response => response.json())
  .then(data => {
    selectedProvince = data[0].name;
    document.getElementById('province-selector').textContent = selectedProvince;
    return fetch(`/api/city?province=${selectedProvince}`);
  })
  .then(response => response.json())
  .then(data => {
    const selectedCity = data[0].name;
    document.getElementById('city-selector').textContent = selectedCity;
    return fetch(`/api/district?province=${selectedProvince}&city=${selectedCity}`);
  })
  .then(response => response.json())
  .then(data => {
    document.getElementById('district-selector').textContent = data[0].name;
  })
  .catch(error => console.error('Request failed:', error));
Tags: javascript

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.