DEV Community

SCDan0624
SCDan0624

Posted on

3 3

Javascript Promise

How to create a Javascript promise

A promise is a function that will complete a task, usually asynchronously, in the future. A promise is always in one of three states:

pending: initial state, neither resolved or rejected

fulfilled: operation was completed successfully

rejected: operation has failed
Enter fullscreen mode Exit fullscreen mode

to create a promise you use the following syntax:

const myPromise = new Promise((resolve, reject) => {

})

Enter fullscreen mode Exit fullscreen mode

How to complete a promise

To actually complete a promise you must add conditions in the function. Using the previous example this is how you would complete the promise:

const myPromise = new Promise((resolve, reject) => {
  if(condition){
  resolve("Promise has been fulfilled")
  } else {
  reject("Promise was rejected")
  }
})

Enter fullscreen mode Exit fullscreen mode

Handle a fulfilled promise with then

Often promises are used with server requests since they can take an unknown amount of time. After you fulfill a promise you usually want to do something with the response from the server. To do this you can use the then method. The then method is executed immediately are the promise is resolved. Here is an example:

myPromise.then(result => {
// Write what you will do with result here
console.log(result)
})
Enter fullscreen mode Exit fullscreen mode

Handle a rejected promise with catch

Catch is used when your promise has been rejected. It will be executed immediately after a the reject method is called.

Here is the syntax:

myPromise.catch(error => {
// Write what you will do with error here
console.log(error)
})
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay