Ad
Promise Is Still Been Returned After Await When Converting Image To Base64 String
I have the method below that converts an image to base64 string
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
Then I decide to use this function like below:
let base_strings = files.map(async file => {
let image = await toBase64(file);
console.dir(image); //this console base string
return image;
});
but when I try to access my base_string array, I still get a promise like below:
I am not exactly sure of what I am doing wrong, I need to be able to get my base64 string in the array.
Ad
Answer
Try using Promise.all()
like this:
let base_strings = files.map(file => {
return toBase64(file);
});
const myImages = await Promise.all(base_strings);
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad