// Scroll to the bottom to add your code
// server
// -----------------------------------------------------
// Imagine this array lives in your server
const items = [
{name: 'Jeans', color: 'blue'},
{name: 'Shoes', color: 'black'}
];
// client
// -----------------------------------------------------
// Function that simulates an AJAX call to our
// imaginary server, where the items 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(items[index]);
}
else {
return cb(null);
}
}, 1000)
}
// Function that returns a promise to search
// a item according to his index
const getItem = (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 item...');
simulateAJAXCall(index, (data) => {
if (data === null) {
reject('Something went wrong!');
}
resolve(data);
});
});
}
// Call getItem, which will return a promise.
// If the promise resolves, then console.log the item,
// if there's an error, it will go to the catch
// block and you can console.log it there.
// Hint: You will have to use "getItem", ".then", and ".catch"
getItem(1).then((item) => console.log(item)).catch((err) => console.log(err))
getItem(10).then((item) => console.log(item)).catch((err) => console.log(err))
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.