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

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

promise

new Promise( (res, rej) => {
  setTimeout(() => res(1), 1000);
}).then( (res) => {
  console.log(res); // 1
  return res*2
}).then( (res) => {
  console.log(res); // 2
});
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

promise javascript

let promise = new Promise(function(resolve, reject){
  try{
  	resolve("works"); //if works
  } catch(err){
    reject(err); //doesn't work
  }
}).then(alert, console.log); // if doesn't work, then console.log it, if it does, then alert "works"
Comment

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! 


Comment

js promise

const executorFunction = (resolve, reject) => {
  if (someCondition) {
      resolve('I resolved!');
  } else {
      reject('I rejected!'); 
  }
}
const myFirstPromise = new Promise(executorFunction);
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

const myPromise = new Promise((resolve, reject) => {  
    let condition;  
    
    if(condition is met) {    
        resolve('Promise is resolved successfully.');  
    } else {    
        reject('Promise is rejected');  
    }
});
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

promise javascript

/*
Promise is a constructor function, so you need to use the new keyword to 
create one. It takes a function, as its argument, with two parameters - 
resolve and reject. These are methods used to determine the outcome of the
promise. 
The syntax looks like this:
*/

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

});

Comment

js promise API

const fetchData = () => {
  fetch('https://api.github.com').then(resp => {
    resp.json().then(data => {
      console.log(data);
    });
  });
};
Comment

promise javascript

let num = 10;
//call back function
const promis = new Promise(function (resolve, reject) {

  if (num > 5) {

    //this resolve method will send data to resoleveData variable
    resolve(" Problem resolved successfully")
  }
  else {
    //this reject method will send data to rejectData variable
    reject("sorry problem couldn't solve")
  }

})
//resoleveData variable
promis.then(function (resolveData) {

  console.log(resolveData)
  //rejectData variable
}).catch(function (rejectData) {

  console.log(rejectData)
})
Comment

js promise

const prom = new Promise((resolve, reject) => {
  resolve('Yay!');
});
 
const handleSuccess = (resolvedValue) => {
  console.log(resolvedValue);
};
 
prom.then(handleSuccess); // Prints: 'Yay!'
Comment

Promises in ES6

function asyncFunc() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
          const result = Math.random();
          result > 0.5 ? resolve(result) : reject('Oppps....I cannot calculate')
        }, 1)
    });
}

for (let i=0; i<10; i++) {
	asyncFunc()
    	.then(result => console.log('Result is: ' + result))
    	.catch(result => console.log('Error: ' + result))
}
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

js promises

let examplePromise = 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);
});
Comment

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
Comment

JavaScript promises MDN

new Promise((resolve, reject) => {
    console.log('Initial');

    resolve();
})
.then(() => {
    throw new Error('Something failed');

    console.log('Do this');
})
.catch(() => {
    console.error('Do that');
})
.then(() => {
    console.log('Do this, no matter what happened before');
});
Comment

Promise

let doSecond = () => {
  console.log('Do second.')
}

let doFirst = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('Do first.')

    resolve()
  }, 500)
})

doFirst.then(doSecond)
Comment

promise js

A promise is an object that may produce a single value some time in the future: 
either a resolved value, or a reason that it’s not resolved 
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

promise

conts trypromises= new Promise((resolve,reject)=>{
	reject()	
  resolve()
});

trypromises.then((data)=>{
	console.log(data)
}).then()

----------------------------------
const proses=(aa)=>{
	return new Promise((resolve,reject)=>{
      	reject()
    	resolve()
    })
};
Comment

promises in javascript

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

js promise

let num = 2;
//call back function
const promis = new Promise(function (resolve, reject) {

  if (num > 5) {

    //this resolve method will send data to resoleveData variable
    resolve(" Problem resolved successfully")
  }
  else {
    //this reject method will send data to rejectData variable
    reject("sorry problem couldn't solve")
  }

})

promis.then(
    //resoleveData variable
    function (resolveData) {

    console.log(resolveData)
    
    }).catch(
    //rejectData variable
    function (rejectData) {

        console.log(rejectData)
    })
Comment

promise definition in javascript

A promise is an object that may produce a single value sometime in the future: either a resolved value, or a reason that it's not resolved (e.g., a network error occurred)
Comment

promise

<script>
    var promise = Promise.resolve(17468);
 
promise.then(function(val) {
    console.log(val);
});
//Output: 17468
</script>
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

promise js

A Promise is in one of these states:

pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
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 promises MDN

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

javascript promise example

/* Testing Grepper
Comment

promise

<script>
    var promise = Promise.resolve(17468);
 
promise.then(function(val) {
    console.log(val);
});
//Output: 17468
</script>
Comment

JavaScript promises MDN

async function foo() {
  try {
    const result = await doSomething();
    const newResult = await doSomethingElse(result);
    const finalResult = await doThirdThing(newResult);
    console.log(`Got the final result: ${finalResult}`);
  } catch(error) {
    failureCallback(error);
  }
}
Comment

JavaScript promises MDN

try {
  const result = syncDoSomething();
  const newResult = syncDoSomethingElse(result);
  const finalResult = syncDoThirdThing(newResult);
  console.log(`Got the final result: ${finalResult}`);
} catch(error) {
  failureCallback(error);
}
Comment

JavaScript promises MDN

function successCallback(result) {
  console.log("Audio file ready at URL: " + result);
}

function failureCallback(error) {
  console.error("Error generating audio file: " + error);
}

createAudioFileAsync(audioSettings, successCallback, failureCallback);
Comment

JavaScript promises MDN

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

JavaScript promises MDN

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

JavaScript promises MDN

doSomething(function(result) {
  doSomethingElse(result, function(newResult) {
    doThirdThing(newResult, function(finalResult) {
      console.log('Got the final result: ' + finalResult);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);
Comment

JavaScript promises MDN

const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);
Comment

JavaScript promises MDN

createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
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

PREVIOUS NEXT
Code Example
Javascript :: jquery ajax download file 
Javascript :: math.max 
Javascript :: flutter response to json 
Javascript :: laravel vue global function 
Javascript :: Different between for of loop and for in loop in js 
Javascript :: jalali moment get milisocnds 
Javascript :: js delete all cookies 
Javascript :: json stringify number 
Javascript :: react-load-animations 
Javascript :: electron ipc from main to renderer 
Javascript :: how to make an array of a value from 1 to the number 
Javascript :: use of split and join 
Javascript :: How to pass data in Link of react-router-dom 
Javascript :: how to receive window.postmessage event in angular 9 
Javascript :: react select error handle 
Javascript :: remove id from array javascript 
Javascript :: jquery copy to clipboard 
Javascript :: javascript number if .00 truncate 
Javascript :: react chart js 2 api data 
Javascript :: date compare in js 
Javascript :: where to find node js logs windows logging node.js howto 
Javascript :: node-disk-storage npm 
Javascript :: Upload different files in different folders using Multer in NodeJs 
Javascript :: reactjs lifecycle class components 
Javascript :: install react-native-safe-area-context 
Javascript :: js for loop plus number 
Javascript :: add class to html tag javascript 
Javascript :: curl post request 
Javascript :: js tostring 
Javascript :: send audio with socket io node js 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =