gpt4 book ai didi

javascript - 将 JS Promise 值赋给变量

转载 作者:行者123 更新时间:2023-12-02 21:02:44 24 4
gpt4 key购买 nike

作为 JS 的初学者,这对我来说有点令人困惑,我正在尝试使用此函数获取图像的 Base64 :

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

当我调用这个函数时,我得到一个 promise ,我可以使用 .then 打印该值,但我无法将函数的返回值分配给变量。

最佳答案

当调用返回Promise的函数时,有两种方法可以从中获取结果:

  1. 使用.then
  2. 使用异步/等待

.然后方法:

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
}

关于javascript - 将 JS Promise 值赋给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61304134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com