how to create a Promise js code example
Example 1: js create a promise
let promise = new Promise((resolve , reject) => {
fetch("https://myAPI")
.then((res) => {
resolve(res);
})
.catch((err) => {
reject(err);
});
});
Example 2: javascript promise
var promise = new Promise(function(resolve, reject) {
if () {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
promise.then(
function(result) { },
function(error) { }
);
Example 3: js promise examples
const loadFile = url => {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url);
request.onload = function() {
if (request.status === 200) {
resolve(request.response);
} else {
reject(Error('An error occurred while loading image. error code:' + request.statusText));
}
};
request.send();
});
};
const openFile = (url, processor) => {
loadFile(url).then(function(result) {
processor(result);
},
function(err) {
console.log(err);
});
};
Example 4: promises in javascript
myPromise.then(
function(value) { },
function(error) { }
);
Example 5: making promises in js
getData()
.then(data => console.log(data))
.catch(error => console.log(error));
Example 6: 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));