Guest User

Untitled

a guest
Jul 19th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. //-----
  2. function rejectSometimes() {
  3. return new Promise((resolve, reject) => {
  4. setTimeout(function() {
  5. const judge = Math.random() >= 0.5;
  6. if (judge) {
  7. resolve(Math.random() * 100)
  8. } else {
  9. reject('dao error');
  10. }
  11. }, 1000);
  12. });
  13. }
  14.  
  15. //-----
  16. async function hogeService() {
  17. const result1 = await rejectSometimes().catch(handleError('hoge fuga!!!!!'));
  18. const result2 = await rejectSometimes().catch(handleError('foo bar*****'));
  19.  
  20. console.log('--------------------');
  21. console.log(result1);
  22. console.log(result2);
  23. console.log('--------------------');
  24.  
  25. return result1 + result2;
  26. }
  27.  
  28. function handleError(message) { // curry
  29. return function(error) {
  30. // エラー時にjkcmnLog.errorLogを呼び出すとか、そういうのを書けばいい
  31. console.log(message);
  32. console.log(error);
  33. throw error;
  34. }
  35. }
  36.  
  37. //-----
  38. hogeService()
  39. .then(result => {
  40. console.log('ok!!!');
  41. console.log(result);
  42. })
  43. .catch((err) => {
  44. console.log('catch!!!');
  45. console.log(err);
  46. });
  47.  
  48. // $ node async_sample.js
  49. // hoge fuga!!!!!
  50. // dao error
  51. // catch!!!
  52. // dao error
  53.  
  54. // $ node async_sample.js
  55. // foo bar*****
  56. // dao error
  57. // catch!!!
  58. // dao error
  59.  
  60. // $ node async_sample.js
  61. // --------------------
  62. // 4.877336342569638
  63. // 64.98860977712235
  64. // --------------------
  65. // ok!!!
  66. // 69.86594611969198
Add Comment
Please, Sign In to add comment