Simple ES6 Promise - 2

by Pritesh Patel

JavaScript

// 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))