js promise function code example

Example 1: javascript promise

var promise = new Promise(function(resolve, reject) {
  // do some long running async thing…
  
  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

//usage
promise.then(
  function(result) { /* handle a successful result */ },
  function(error) { /* handle an error */ }
);

Example 2: promise js

We use promise to make a  AsyncFunction, cose simetime we have to wait that function give 
us some result.
Example, if we use ajax we have await ajax data or statament.
_____________________________________
Make a simple example.
_____________________________________
var asyncronus_function= (number)=>
		{
			return new Promise( (accept, reject)=>
			{
			})
		}                 
_____________________________________
this function return a promise Object, thet required a function executor
this functions (accept, reject) are defined in the executor 
function, that was needed in promise constructor.
Syntax: new Promise (executor)
executor= (accept, reject) =>{}

if function end well we return a accept(), otherwise reject()
_____________________________________
Let complete asyncronus_function
_____________________________________
var asyncronus_function= (number)=>
		{
			return new Promise( (accept, reject)=>
			{
				if(number>10)
				return accept("my first async");
				return reject("my first async error")
			})

		}
if it dont return any of this 2 function, Promise state is [PENDING] ,
if return accept is [RESOLVED]  end if return reject is [REJECTED]
_____________________________________
how we can retrieve accept or reject?
_____________________________________
there is two methods really important, that we have to consider afther we call this function
1) .then(function(error){}) is call when promise state is [RESOLVED]
2) .error(function(error){}) is call when promise state is [REJECTED]
3) do nothing if [PENDING]
_____________________________________
let call asyncronus_function()!!! 
_____________________________________
	asyncronus_function(MY_NUMBER).then(function(data)
        {
			console.log(data)
    	}).catch(error => 
        {
      			console.log(error)
    	});
		
if  MY_NUMBER> 10 ,asyncronus_function print data : OUTPUT my first async
if MY_NUMBER<10 , asyncronus_function print error : OUTPUT my first async error
HOPE it halp and have a nice day!

Example 3: promise javascript

const promiseA = new Promise( (resolutionFunc,rejectionFunc) => {
    resolutionFunc(777);
});
// At this point, "promiseA" is already settled.
promiseA.then( (val) => console.log("asynchronous logging has val:",val) );
console.log("immediate logging");

// produces output in this order:
// immediate logging
// asynchronous logging has val: 777

Example 4: what is promise in javascript

Promises make async javascript easier as they are easy to use and write than callbacks. Basically , promise is just an object , that gives us either success of async opertion or failue of async operations

Example 5: javascript promises

var posts = [
  {name:"Mark42",message:"Nice to meet you"},
  {name:"Veronica",message:"I'm everywhere"}
];

function Create_Post(){
  setTimeout(() => {
    posts.forEach((item) => {
      console.log(`${item.name} --- ${item.message}`);
    });
  },1000);
}

function New_Post(add_new_data){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
     posts.push(add_new_data);
      var error = false;
      if(error){
        reject("Something wrong in , Try setting me TRUE and check in console");
      }
      else{
        resolve();
      }
    },2000);
  })
}

New_Post({name:"War Machine",message:"I'm here to protect"})
    .then(Create_Post)
    .catch(err => console.log(err));

Tags:

Misc Example