Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Json Promise Code Sample

code

Uploaded by

biit Biit
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Json Promise Code Sample

code

Uploaded by

biit Biit
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

let myPromise = new Promise(function(resolve, reject) {

// some code that t

JavaScript Promise
Last Updated : 13 Aug, 2024
JavaScript promises might sound a bit complicated at first, but once you get a
clear understanding of them, they make working with code that takes time to
complete, like fetching data from a website or waiting for a timer, much easier to
manage. Let’s break down what promises are and how you can use them.

What is a Promise?
A promise in JavaScript is like a container for a future value. It is a way of
saying, “I don’t have this value right now, but I will have it later.” Imagine you
order a book online. You don’t get the book right away, but the store promises to
send it to you. While you wait, you can do other things, and when the book arrives,
you can read it.

In the same way, a promise lets you keep working with your code while waiting for
something else to finish, like loading data from a server. When the data is ready,
the promise will deliver it.

How Does a Promise Work?


A promise can be in one of three states:

Pending: The promise is waiting for something to finish. For example, waiting for
data to load from a website.
Fulfilled: The promise has been completed successfully. The data you were waiting
for is now available.
Rejected: The promise has failed. Maybe there was a problem, like the server not
responding.
When you create a promise, you write some code that will eventually tell the
promise whether it was successful (fulfilled) or not (rejected).

Syntax
let promise = new Promise(function(resolve, reject){
//do something
});
Parameters

The promise constructor takes only one argument which is a callback function
The callback function takes two arguments, resolve and reject
Perform operations inside the callback function and if everything went well then
call resolve.
If desired operations do not go well then call reject.
Creating a Promise
Let’s see how to create the promise in JavaScript:

Here we have created a new promise using the Promise constructor. Inside the
promise, there are two functions: resolve and reject. If everything goes well, we
call resolve and pass the result. If something goes wrong, we call reject and pass
an error message.

You might also like