Guest User

Untitled

a guest
Jul 18th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. 1. The function after `await someFunc()` need to return a promise. Otherwise it will not await and exit from the function. The function below will simply exit and won't wait till the background process is finished. Since async functions are waiting for Promises. The keyword await makes JavaScript wait until that promise settles and returns its result.
  2.  
  3. ```js
  4. const hello4 = () => setTimeout(() => console.log('Hello from Hello4'), 5000)
  5.  
  6. const asycFunc = async() => {
  7. await hello4()
  8. return
  9. }
  10. ```
  11.  
  12. But if do return a promise:
  13.  
  14. ```js
  15. const hello4 = () => {
  16. return new Promise(resolve => {
  17. setTimeout(() => resolve(console.log('Hello from Hello4')), 2000)
  18. })
  19. }
  20.  
  21. const asycFunc = async() => {
  22. await hello4()
  23. return
  24. }
  25.  
  26. // Hello from Hello4
  27.  
  28. ```
  29.  
  30. 2. If something doesn't return a promise you need to promisify it. For instance, you can promisify the Amazon SDK by adding `.promise()`. So you can use `async/await` functions. The AWS.Request.promise method provides a way to call a service operation and manage asynchronous flow instead of using callbacks.
  31.  
  32. ```js
  33. var s3 = new AWS.S3({apiVersion: '2006-03-01', region: 'us-west-2'});
  34. var params = {
  35. Bucket: 'bucket',
  36. Key: 'example2.txt',
  37. Body: 'Uploaded text using the promise-based method!'
  38. };
  39. var putObjectPromise = s3.putObject(params).promise();
  40. putObjectPromise.then(function(data) {
  41. console.log('Success');
  42. }).catch(function(err) {
  43. console.log(err);
  44. });
  45. ```
  46.  
  47. 3. Use `try{} catch (error) {}` to do proper error handling
  48.  
  49. ```js
  50. const hello4 = () => {
  51. return new Promise(resolve => {
  52. setTimeout(() => resolve(console.log('Hello from Hello4')), 2000)
  53. })
  54. }
  55.  
  56. const asycFunc = async() => {
  57. try {
  58. await hello4()
  59. return
  60. }
  61. catch (error) {
  62. console.log(error)
  63. }
  64. }
  65.  
  66. // Hello from Hello4
  67.  
  68. ```
Add Comment
Please, Sign In to add comment