Simple ES6 Promise
by j0b02py
Babel + JSX
// 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.
// ADD YOUR CODE HERE
getItem(0)
.then(item => {
console.log('item:', item); // Success!
})
.catch(function(error){console.log(error)})
// Hint: You will have to use "getItem", ".then", and ".catch"