🖍️
Developer Note
  • Welcome
  • Git
    • Eslint & Prettier & Stylelint & Husky
  • Programming Language
    • JavaScript
      • Script Async vs Defer
      • Module
      • Const VS Let VS Var
      • Promise
      • Event Loop
      • Execution Context
      • Hoisting
      • Closure
      • Event Buddling and Capturing
      • Garbage Collection
      • This
      • Routing
      • Debounce and Throttle
      • Web Component
      • Iterator
      • Syntax
      • String
      • Array
      • Object
      • Proxy & Reflect
      • ProtoType
      • Class
      • Immutability
      • Typeof & Instanceof
      • Npm (Node package manager)
    • TypeScript
      • Utility Type
      • Type vs Interface
      • Any vs Unknown vs Never
      • Void and undefined
      • Strict Mode
      • Namespace
      • Enum
      • Module
      • Generic
    • Python
      • Local Development
      • Uv
      • Asyncio & Event loop
      • Context Manager
      • Iterator & Generator
      • Fast API
      • Pydantic & Data Class
    • Java
      • Compilation and Execution
      • Data Type
      • Enumeration
      • Data Structure
      • Try Catch
      • InputStream and OutputStream
      • Concurrent
      • Unicode Block
      • Build Tools
      • Servlet
      • Java 8
  • Coding Pattern
    • MVC vs MVVM
    • OOP vs Functional
    • Error Handling
    • MVC vs Flux
    • Imperative vs Declarative
    • Design Pattern
  • Web Communication
    • REST API
      • Web Hook
      • CORS issue
    • HTTPS
    • GraphQL
      • REST API vs GraphQL
      • Implementation (NodeJS + React)
    • Server-Sent Event
    • Web Socket
    • IP
    • Domain Name System (DNS)
  • Frontend
    • Progressive Web App (PWA)
    • Single Page & Multiple Page Application
    • Search Engine Optimiaztion (SEO)
    • Web bundling & Micro-frontend
      • Webpack
        • Using Webpack to build React Application
        • Using Webpack to build react library
      • Vite
      • Using rollup to build react library
      • Implementing micro frontend
    • Web Security
      • CSRF & Nonce
      • XSS
      • Click hijacking
    • Cypress
    • CSS
      • Core
        • Box Model
        • Inline vs Block
        • Flexbox & Grid
        • Pseudo Class
        • Position
      • Tailwind CSS
        • Shadcn
      • CSS In JS
        • Material UI
    • React
      • Core
        • Component Pattern
        • React Lazy & Suspense
        • React Portal
        • Error Boundary
        • Rendering Methods
        • Environment Variable
        • Conditional CSS
        • Memo
        • Forward Reference
        • High Order Component (HOC) & Custom Hook
        • TypeScript
      • State Management
        • Redux
        • Recoil
        • Zustand
      • Routing
        • React Router Dom
      • Data Fetching
        • Axios & Hook
        • React Query
        • Orval
      • Table
        • React Table
      • Form & Validation
        • React Hook Form
        • Zod
      • NextJS
        • Page Router
        • App Router
      • React Native
    • Angular
    • Svelte
      • Svelte Kit
  • Backend
    • Cache
      • Browser Cache
      • Web Browser Storage
      • Proxy
      • Redis
    • Rate limit
    • Monitoring
      • Logging
      • Distributed Tracing
    • Load Test
    • Encryption
    • Authentication
      • Password Protection
      • Cookie & Session
      • JSON Web Token
      • SSO
        • OAuth 2.0
        • OpenID Connect (OIDC)
        • SAML
    • Payment
      • Pre-built
      • Custom
    • File Handling
      • Upload & Download (Front-end)
      • Stream & Buffer
    • Microservice
      • API Gateway
      • Service Discovery
      • Load Balancer
      • Circuit Breaker
      • Message Broker
      • BulkHead & Zipkin
    • Elastic Search
    • Database
      • SQL
        • Group By vs Distinct
        • Index
        • N + 1 problem
        • Normalization
        • Foreign Key
        • Relationship
        • Union & Join
        • User Defined Type
      • NOSQL (MongoDB)
      • Transaction
      • Sharding
      • Lock (Concurrency Control)
    • NodeJS
      • NodeJS vs Java Spring
      • ExpressJS
      • NestJS
        • Swagger
        • Class Validator & Validation Pipe
        • Passport (Authentication)
      • Path Module
      • Database Connection
        • Integrating with MYSQL
        • Sequalize
        • Integrating with MongoDB
        • Prisma
        • MikroORM
        • Mongoose
      • Streaming
      • Worker Thread
      • Passport JS
      • JSON Web Token
      • Socket IO
      • Bull MQ
      • Pino (Logging)
      • Yeoman
    • Spring
      • Spring MVC
      • Spring REST
      • Spring Actuator
      • Aspect Oriented Programming (AOP)
      • Controller Advice
      • Filter
      • Interceptor
      • Concurrent
      • Spring Security
      • Spring Boot
      • Spring Cloud
        • Resilience 4j
      • Quartz vs Spring Batch
      • JPA and Hibernate
      • HATEOS
      • Swagger
      • Unit Test (Java Spring)
      • Unit Test (Spring boot)
  • DevOp
    • Docker
    • Kubernetes
      • Helm
    • Nginx
    • File System
    • Cloud
      • AWS
        • EC2 (Virtual Machine)
        • Network
        • IAM
          • Role-Service Binding
        • Database
        • Route 53
        • S3
        • Message Queue
        • Application Service
        • Serverless Framework
        • Data Analysis
        • Machine Learning
        • Monitoring
        • Security
      • Azure
        • Identity
        • Compute Resource
        • Networking
        • Storage
        • Monitoring
      • Google Cloud
        • IAM
          • Workload Identity Federation
        • Compute Engine
        • VPC Network
        • Storage
        • Kubernetes Engine
        • App Engine
        • Cloud function
        • Cloud Run
        • Infra as Code
        • Pub/Sub
    • Deployment Strategy
    • Jenkins
    • Examples
      • Deploy NextJS on GCP
      • Deploy Spring on Azure
      • Deploy React on Azure
  • Domain Knowledge
    • Web 3
      • Blockchain
      • Cryptocurrency
    • AI
      • Prompt
      • Chain & Agent
      • LangChain
      • Chunking
      • Search
      • Side Products
Powered by GitBook
On this page
  • What is promise?
  • Why need promise?
  • Status of Promise
  • Structure of Promise
  • Rewrite by using promise
  • Feature
  • Callback
  • Chain
  • Method
  • Async & Await
  • Introduction
  • Return Value
  • In sequence vs Concurrent

Was this helpful?

  1. Programming Language
  2. JavaScript

Promise

PreviousConst VS Let VS VarNextEvent Loop

Last updated 7 months ago

Was this helpful?

What is promise?

  • A is an object consisting of state, result, callback handler

  • When the status is changed to success/ failed, the callback function will be put into micro-task queue

Why need promise?

  • As we know, javascript is single-thread. If async function is arranged, the callback will be done at the end of the function, which is not the same as our expectation. Therefore, we need promise to queue up the handler. For example: For the api call, we might want trigger the handler in sequence after the data is got from api end point.

  • Case 1 :

const test = () => {
    console.log('Program Start');
    setTimeout(() => { console.log('async Function');}, 0);
    console.log('End');
}
test();

// Expectation:
// Program Start
// async Function 
// End

// Output:
// Program
// End
// async Function
  • Ajax method is also a typical example. Let's take axios as an example

  • Case 2:


const test = () => {    
    let data = {};
    data = axios.get(url ,{});
    console.log('Data:',data);
}

test();

// Expectation:
// data: real data

// Output:
// data: {}

Status of Promise

  • Pending: the promise function is progressing

  • Fulfilled: the promise function is successful

  • Rejected: the promise function is failed

Structure of Promise

  • Then : Promise return successfully

  • Catch : Failed to return promise, to do error handling

  • Final : The end of the promise function

  • Example:

const promise = () => {
  return new Promise((resolve,reject) => {
    // get 0 or 1 randomly
    const num = Math.random() > 0.5 ? 1 : 0;
    if (num) { 
      // declare the return value when fulfilled
      resolve('success ya!'); 
    }
    else{
      // declare the return value when rejected 
      reject('failed');
    }        
  })
}

const test = () => {
  promise().then((value)=>
  {
    console.log(value); // success ya!  
  }).catch((error)=>{
    //to do error handling
    console.log(error); // failed
  }).final(()=>{
    console.log("finished"); // finished
  })
}

test();

// Output:
// successya!!! / failed
// finished

Rewrite by using promise

  • Case 1:

const timeout = () => {
    return new Promise((resolve, reject)=>{
        setTimeout(() => {
            console.log('async Function');
            resolve("success");        
        }, 0);
    })
}

const test = () => {
    timeout.then((value)=>{
        console.log('End');
        console.log(value);
    })
}

test();
// Output:
// async Function
// End
  • Case 2: (Actually axios is a function with promise, so we don't need to make a new promise function)

const test = () => {
    let data = {};
    axiox.get(url,{}).then((data)=>{
        data = success;
        console.log('data:',data);
    })
}
// Output:
// data: real data

Feature

Callback

  • The resolve and reject is a callback of the promise, so that it will be triggered at last

Chain

doSomething()
  .then(function (result) {
    return doSomethingElse(result);
  })
  .then(function (newResult) {
    return doThirdThing(newResult);
  })
  .then(function (finalResult) {
    console.log(`Got the final result: ${finalResult}`);
  })
  .catch(failureCallback);

Method

Promise All

  • Run multiple promise functions at the same time and then return the result

const promise = (input) =>{
    return new Promise((resolve,reject)=>{
        resolve(input);
    })
}

const test = () =>{
    Promise.all([promise(1),promise(2),promise(3)]).then((value)=>{
        console.log(value);
    })
    //or
    // const value = await Promise.all([promise(1),promise(2),promise(3)]);
}

test();

// Output:
// [1,2,3]

Promise Race

  • Compare and return the promise that is the fastest to be resolved

const promise1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'one');
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then((value) => {
  console.log(value);
  // Both resolve, but promise2 is faster
});
// Expected output: "two"

Async & Await

Introduction

  • With long chaining of promise, which may make the code not readable

const listOfIngredients = [];

doSomething()
  .then((url) => {
    // `return` keyword now included in front of fetch call.
    return fetch(url)
      .then((res) => res.json())
      .then((data) => {
        listOfIngredients.push(data);
      });
  })
  .then(() => {
    console.log(listOfIngredients);
    // listOfIngredients will now contain data from fetch call.
  });
  • In order to make code more clean and looks exactly like synchronous code, we can use async await to replace the chaining

async function logIngredients() {
  const url = await doSomething();
  const res = await fetch(url);
  const data = await res.json();
  listOfIngredients.push(data);
  console.log(listOfIngredients);
}

Return Value

  • The return value must be a promise

In sequence vs Concurrent

const testAsync = async(input) => {
    const data = await Promise.resolve(input);
    console.log(data);
}


const inSequence = async() => {
  const array = [1,2,3];
  for(const i of array){
    await testAsync(i);
  }
}

const concurrent = async()=>{
  await Promise.all([1,2,3].map((i)=>testAsync(i)));
}

// avoid using foreach for promise due to unexpected behaviors
// ref: https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
Promise