Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript promise

let conditions=true;


const proms= new Promise((resolve, reject) => {
    setTimeout(() => {
        if (conditions) {
            resolve ("Hello")
        } else {
            reject ("This condition faild")
        }
    }, 2000);
});


proms.then((result) => {
    console.log(result);
})
.catch(function(error){
    console.log(error);
});

Comment

new promise function

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('foo');
  }, 300);
});

myPromise
  .then(handleResolvedA, handleRejectedA)
  .then(handleResolvedB, handleRejectedB)
  .then(handleResolvedC, handleRejectedC);
Comment

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 */ }
);
Comment

what is promise in javascript

Promises are used to handle asynchronous operations in JavaScript.
They are easy to manage when dealing with multiple asynchronous operations
where callbacks can create callback hell leading to unmanageable code.
Comment

javascript promise example basic

const anotherPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('this is the eventual value the promise will return');
  }, 300);
});

// CONTINUATION
anotherPromise
.then(value => { console.log(value) })
Comment

javascript promise

let promise = new Promise((resolve,reject)=>{
                try {
                    resolve("some data");
                } catch (error) {
                    reject(error);
                }
            })
            
            promise.then(function (data) {
                console.log(data);
            },function (error) {
                console.error(error);
            })
Comment

promise in javascript

const studentRol=new Promise((resolve, reject) => {
    setTimeout(()=>{
        /**this function will give the value Of tageted studebt Roll number  */
           let RollOffStd=[1,2,3,4,5,6,7,8];
        
            for (let index = RollOffStd[RollOffStd.length-1]+1 ; index <50; index++) {
                RollOffStd.push(index)
                
            }
            
            resolve( RollOffStd)
            
            reject('My name is Noor mohammad ')
      

    },1000)
})


const mybiodata=(gRollOfStudent /* this is First parameter OF ( mybiodata function ) and You can change parameter value  */)=>{
    return new Promise((resolve, reject) => {
        setTimeout((x) => {
           let  bio={
                myname : 'Noor mohammad Patwary ' ,
                age : 25 ,
            }

            resolve(`my name is ${bio.myname } and my age =  ${bio.age } and my roll is =${x} ` )
        }, 1000,gRollOfStudent);
    })
}

studentRol.then(( RollOfStudent)=>{
    console.log(RollOfStudent); /** From here we are gating the Value OF student roll number  */
    mybiodata(RollOfStudent[1] /* this is First Argument OF ( mybiodata function )*/).then((fff)=>{
        console.log(fff);
    })

}).catch((x)=>{
    console.log(x);
})



Comment

promise in javascript

/*
A promise is a building object of JavaScript, using it we can easily do 
asynchronous tasks. Also, the concept that is used to create clean code 
basically promises.
*/
//Promise
let firstPromise = new Promise((resolved, reject) => {
    let fullName = 'Muhammad Shahnewaz';
    setTimeout(() => resolved(fullName), 3000);  //we need to use setTimeout() 
}).then((name) => {
    console.log('I am ' + name);    //Muhammad Shahnewaz
});
Comment

javascript Program with a Promise

const count = true;

let countValue = new Promise(function (resolve, reject) {
    if (count) {
        resolve("There is a count value.");
    } else {
        reject("There is no count value");
    }
});

console.log(countValue);
Comment

Create A Promise In JavaScript

async function abc() 
{ 	
	const myPromise = new Promise(function(resolve, reject) {
   resolve("hello world");
});
let y= await myPromise;
console.log(y);
/*"hello world*/
	}
Comment

javascript promise


const myScore=500 ;

function checkNumnbner() {
    console.log('Course Enrolment Process');
    const myPromise=new Promise((resolve , reject)=>{
        if (myScore >= 80) {
            resolve("First one is true");
        }else{
            setTimeout(() => {
                reject("SORRY we CANT offering you a job")
            }, 2000);
        }
     })
    return myPromise;
    
}

function offerLater() {
    const newPromise2=new Promise((resolve) => {
        setTimeout(() => {
            resolve("congratulation we are offering you a job")
        }, 500);
        
    })
    return newPromise2;
}

function thanksT() {
    const End= new Promise(() => {
        
           setTimeout(()=>{
            console.log(('Thanks to try'));
           },2000)
        
    })
    return End
}

checkNumnbner()
.then(offerLater)
.then(value=> console.log(value))
.then(thanksT)

.catch((error)=>{
    console.log(error);
})
Comment

promise syntax for javascript

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

  myResolve(); // when successful
  myReject();  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);
Comment

javascript Create a Promise

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

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));
Comment

promise syntax in js


// make new promise ... so this object will promise us that it will hold an Asynchronous action
// some times promise resolve and some times promise get rejected
const A = new Promise((resolve, reject) => {
    setTimeout(() => {
        // here we pass argument if promise get resolved
        resolve('Done');

        // here we pass argument if promise get rejected
        reject('Didn"t');
    }, 3000);
});


// design handling callback function for resolve 
let handleResolvedA = (massage)=>{console.log(massage)}

// design handling callback function for reject 
let handleRejectedA = (massage)=>{console.log(massage)}


// do handling for both
A.then(handleResolvedA, handleRejectedA)
Comment

javascript promise

var myImage = document.querySelector('#example');

function loaded() {
  // bien, la imagen cargó
}

if (myImage.complete) {
  loaded();
} else {
  myImage.addEventListener('load', loaded);
}

myImage.addEventListener('error', function() {
  // ocurrió un imprevisto
});
Comment

Simplest Promise Example

let hw = await new Promise((resolve)=>{
resolve(“HELLO WORLD”);

})

console.log(hw);
 
/*basically in resolve(whatever') the whatever is returned*/
/*hw will console.log out "HELLO WORLD" */
Comment

promises in javascript

myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);
Comment

promise in js

myPromise
.then(handleResolvedA)
.then(handleResolvedB)
.then(handleResolvedC)
.catch(handleRejectedAny)
.finally(handleComplition)
Comment

javascript promises

let dataIsLoading = true;

promise
  .then(data => {
    // do something with data
  })
  .catch(error => {
   // do something with error
  })
  .finally(() => {
    dataIsLoading = false;
  })
Comment

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
Comment

javascript promise

const maPromesse = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('toto');
  }, 300);
});

maPromesse
  .then(gestionnaireSuccesA, gestionnaireEchecA)
  .then(gestionnaireSuccesB, gestionnaireEchecB)
  .then(gestionnaireSuccesC, gestionnaireEchecC);
Comment

javascript promise example

/* Testing Grepper
Comment

js promise example

function examplePromise(){
  let promiseToReturn = new Promise(function (resolve, reject) {
    let sum;
    setTimeout(function(){
      sum = 5 + 6;
      if(sum > 10) {
        resolve(sum);
      }else{
        reject('The promise has been rejected');
      }     
    }, 2000);
  });
  return promiseToReturn;
}

console.log('some piece of code');
examplePromise().then(function(result){
  console.log(result);
}).catch(function(error){
  console.log(error);
});
console.log('another piece of code');
Comment

JavaScript Promises

// returns a promise
let countValue = new Promise(function (resolve, reject) {
   reject('Promise rejected'); 
});

// executes when promise is resolved successfully
countValue.then(
    function successValue(result) {
        console.log(result); // Promise resolved
    },
 )
Comment

JavaScript Promise Methods

Method	Description
all(iterable)	Waits for all promises to be resolved or any one to be rejected
allSettled(iterable)	Waits until all promises are either resolved or rejected
any(iterable)	Returns the promise value as soon as any one of the promises is fulfilled
race(iterable)	Wait until any of the promises is resolved or rejected
reject(reason)	Returns a new Promise object that is rejected for the given reason
resolve(value)	Returns a new Promise object that is resolved with the given value
catch()	Appends the rejection handler callback
then()	Appends the resolved handler callback
finally()	Appends a handler to the promise
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript math round 
Javascript :: sort function explained javascript 
Javascript :: class declaration in javascript 
Javascript :: mongoose schema example 
Javascript :: export default function react 
Javascript :: add to map javascript 
Javascript :: js date 
Javascript :: react native icons 
Javascript :: sequelize update 
Javascript :: filter bootstrap 
Javascript :: anti aliasing 
Javascript :: type js 
Javascript :: vanilla js 
Javascript :: change url without reloading the page 
Javascript :: javascript operators 
Javascript :: mvc asp.net partial view from js 
Javascript :: mongoose array includes 
Javascript :: for loop in react native 
Javascript :: simulate mouse click javascript 
Javascript :: how to detect a section is visible in jquery 
Javascript :: destructuring assignment in javascript 
Javascript :: javascript merge multidimensional array 
Javascript :: javaScript Math.log() Method 
Javascript :: javaScript add() Method 
Javascript :: javascript first or default 
Javascript :: find the second largest number in array javascript 
Javascript :: Generate random phone numbers in POSTMAN 
Javascript :: sveltekit disable ssr 
Javascript :: fetch log api response time 
Javascript :: macam macam looping javascript 
ADD CONTENT
Topic
Content
Source link
Name
3+3 =