Javascript 为变量赋值
作为JS中的初学者,我觉得有点困惑,我正在尝试使用以下函数获取图像的base64:Javascript 为变量赋值,javascript,promise,es6-promise,Javascript,Promise,Es6 Promise,作为JS中的初学者,我觉得有点困惑,我正在尝试使用以下函数获取图像的base64: const convertFileToBase64 = file => new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror =
const convertFileToBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
})
当我调用此函数时,我得到一个可以使用的承诺。然后打印值,但我无法将函数的返回值赋给变量。当调用返回承诺的函数时,有两种方法可以从中获得结果:
。然后
convertFileToBase64(myFile)
.then(result => {
// do something with the result within this little function
})
.catch(err => {
// handle any error
});
// must be inside an async function
async function doSomething() {
const result = await convertFileToBase64(myFile); // wait and assign result to variable
// do something with the result
// errors can get handled by whoever calls this async function
}
异步/等待方法:
convertFileToBase64(myFile)
.then(result => {
// do something with the result within this little function
})
.catch(err => {
// handle any error
});
// must be inside an async function
async function doSomething() {
const result = await convertFileToBase64(myFile); // wait and assign result to variable
// do something with the result
// errors can get handled by whoever calls this async function
}
你能展示一下你是如何调用这个函数的吗?返回值应该是
中第一个函数的参数。然后是中的。然后(result=>{})
我有这个函数const-handleFile=async(file)=>{return-await-convertFileToBase64(file)}
在另一个函数const-res=handleFile(icon)中调用
printing res将输出一个promise,因此您应该使用res。然后(result=>{/*use result*/}
如我的回答中所述,我知道我可以。然后
访问该值,但假设我想这样做让finalResult={}convertFileToBase64(图标)。然后(r=>{finalResult=r})console.log('final result:',finalResult)
如果您不想使用,则输出将是未定义的。然后
您必须使用等待