Created
March 14, 2017 08:23
-
-
Save welll/6f99b96db22fe8975c1e112ab0dc62ee to your computer and use it in GitHub Desktop.
Callback Hell Async/Await
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
| const AWS = require(`aws-sdk`) | |
| const fs = require(`fs`) | |
| const path = require(`path`) | |
| const dir = `./sample-dir` | |
| const bucket = `bucket-name` | |
| const s3bucket = new AWS.S3({params: {Bucket: bucket}}) | |
| async function readDirAsync(path) { | |
| return new Promise(function (resolve, reject) { | |
| fs.readdir(path, function (error, result) { | |
| if (error) { | |
| reject(error); | |
| } else { | |
| resolve(result); | |
| } | |
| }) | |
| }) | |
| } | |
| function readFileAsync(path) { | |
| return new Promise(function (resolve, reject) { | |
| fs.readFile(path, function (error, result) { | |
| if (error) { | |
| reject(error) | |
| } else { | |
| resolve(result) | |
| } | |
| }) | |
| }) | |
| } | |
| function s3UploadAsync(params){ | |
| return new Promise(function (resolve, reject) { | |
| s3bucket.upload(params, function (error, result) { | |
| if (error) { | |
| reject(error) | |
| } else { | |
| resolve(result) | |
| } | |
| }) | |
| }) | |
| } | |
| async function unlinkAsync(path) { | |
| return new Promise(function (resolve, reject) { | |
| fs.unlink(path, function (error, result) { | |
| if (error) { | |
| reject(error) | |
| } else { | |
| resolve(result) | |
| } | |
| }) | |
| }) | |
| } | |
| async function start(){ | |
| const files = await readDirAsync(dir) | |
| files.forEach( async (fileName, fileIndex) => { | |
| const filePath = path.resolve(dir, fileName) | |
| const data = await readFileAsync(`${filePath}`) | |
| const params = { | |
| Key: fileName, | |
| Body: data | |
| }; | |
| await s3UploadAsync(params) | |
| await unlinkAsync(filePath) | |
| }) | |
| } | |
| start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment