Skip to content

Instantly share code, notes, and snippets.

@sohel-rana
Last active May 5, 2018 08:17
Show Gist options
  • Save sohel-rana/fc9f5ca8d91f18232e026e62c212968e to your computer and use it in GitHub Desktop.
Save sohel-rana/fc9f5ca8d91f18232e026e62c212968e to your computer and use it in GitHub Desktop.
A promise sample
function find (x) {
if (x === 10) {
return Promise.resolve(10);
} else {
return new Promise(function (resolve, reject) {
try {
if (x === 0) {
throw ('0 not allowed');
}
let t = parseInt(x);
return resolve(t);
} catch (e) {
return reject({error: e});
}
});
}
}
find(5).then(function (data) {
console.log(data);
});
find(0).then(function (data) {
console.log(data);
}).catch(function (e) {
console.log(e);
});
// Promise chaining
function getData5 () {
return find(5).then(function (data) {
return data;
});
}
function getData0 () {
return find(0).then(function (data) {
return data;
}).catch(function (e) {
return e;
});
}
function getData10 () {
return find(10).then(function (data) {
return data;
}).catch(function (e) {
console.log(e);
});
}
getData5().then(function (response) {
console.log('Promise chain with Promise object: ', response);
});
getData0().then(function (response) {
console.log(response);
});
getData10().then(function (response) {
console.log('Promise chain with Promise.resolve(): ', response);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment