// ES6 Promise Example
// server
// -----------------------------------------------------
// Imagine this array lives in your server
const people = [
{name: 'John Doe', age: '30'},
{name: 'Jane Doe', age: '24'}
];
// client
// -----------------------------------------------------
// function that simulates an AJAX call to our
// imaginary server, where the people array lives.
// The call may succeed or fail.
const simulateAJAXCall = (index, cb) => {
let chance = Math.random();
let isSuccess= (chance <= 0.80) ? true : false;
return setTimeout(() => {
if (isSuccess) {
return cb(people[index]);
}
else {
return cb(null);
}
}, 1000)
}
// Function that returns a promise to search
// a person according to his index
const getPerson = (index) => {
// The promise resolves if the data comes back
// successfully and it rejects in case of an error
return new Promise((resolve, reject) => {
console.log('fetching person...');
simulateAJAXCall(index, (data) => {
if (data === null) {
reject('Something went wrong!');
}
resolve(data);
});
});
}
const troll = () => {
}
// Call getPerson, which will return a promise.
// If the promise resolves, then log the person,
// if there's an error, it will go to the catch
// block and be handled there.
getPerson(0).then(person => {
console.log(person);
}).catch(error => {
console.log(error);
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.