1function doSomething() {
2 return new Promise((resolve, reject) => {
3 console.log("It is done.");
4 // Succeed half of the time.
5 if (Math.random() > .5) {
6 resolve("SUCCESS")
7 } else {
8 reject("FAILURE")
9 }
10 })
11}
12
13const promise = doSomething();
14promise.then(successCallback, failureCallback);
1function myAsyncFunction(url) {
2 return new Promise((resolve, reject) => {
3 const xhr = new XMLHttpRequest();
4 xhr.open("GET", url);
5 xhr.onload = () => resolve(xhr.responseText);
6 xhr.onerror = () => reject(xhr.statusText);
7 xhr.send();
8 });
9}
1var posts = [
2 {name:"Mark42",message:"Nice to meet you"},
3 {name:"Veronica",message:"I'm everywhere"}
4];
5
6function Create_Post(){
7 setTimeout(() => {
8 posts.forEach((item) => {
9 console.log(`${item.name} --- ${item.message}`);
10 });
11 },1000);
12}
13
14function New_Post(add_new_data){
15 return new Promise((resolve, reject) => {
16 setTimeout(() => {
17 posts.push(add_new_data);
18 var error = false;
19 if(error){
20 reject("Something wrong in </>, Try setting me TRUE and check in console");
21 }
22 else{
23 resolve();
24 }
25 },2000);
26 })
27}
28
29New_Post({name:"War Machine",message:"I'm here to protect"})
30 .then(Create_Post)
31 .catch(err => console.log(err));