Last active
May 5, 2018 08:17
-
-
Save sohel-rana/fc9f5ca8d91f18232e026e62c212968e to your computer and use it in GitHub Desktop.
A promise sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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