我在这里看到了几个示例,并根据这些示例准备了解决方案。但我仍然得到Promise__proto__: Promise[[PromiseStatus]]: "pending[[PromiseValue]]: undefined
我试图将我的base 64数据存储到我的base64变量中。请让我知道我的代码和有效的解决方案出了什么问题。

下面是我的尝试:



import React, { Component } from 'react'
import { DropzoneArea, DropzoneDialog } from 'material-ui-dropzone'
import Button from '@material-ui/core/Button';


async function getBaseData(selectedFile) {
    let base64;
    var fileToLoad = selectedFile[0];
    base64 = await getBase64(fileToLoad);
    return base64; //This returns me PromiseStatus Pending
}

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
        return Promise.resolve(reader.result)
    });
}

export class ImageUploader extends Component {
    constructor(props) {
        super(props);
        this.state = {
            files: [],
            image: null,
        };
    }
    handleImageChange(files) {
        const { imageCallback } = this.props
        imageCallback(getBaseData(files)); // By this callback i am trying to pass my base64 string to other component
    }
    render() {
        return (
            <DropzoneArea
                acceptedFiles={['image/*']}
                filesLimit={1}
                maxFileSize={10000000}
                //showPreviews={false}
                onChange={this.handleImageChange.bind(this)}
            />
        )
    }
}

最佳答案

问题是getBaseData是一个异步函数,但是您仍然需要等待它解决。

也可以尝试“等待”:

handleImageChange(files) {
            const { imageCallback } = this.props;
            async function wrap(){
               const result = await getBaseData(files); //result should be a value here and not promise
               imageCallback(result);
            }
            wrap(); // call the async function which will await the getBaseData and use your callback

        }

07-28 07:24