简体   繁体   English

将 JS 承诺值分配给变量

[英]Assigning JS promises value to a variable

As a starter in JS promises it is a bit confusing to me, I am trying to get a base64 of an image using this function:作为 JS 的初学者,这对我来说有点令人困惑,我正在尝试使用此 function 获取图像的 base64:

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

when I call this function I get a promise I can use.then to print the value, but I cannot assign the returned value of the function to a variable.当我调用这个 function 时,我得到一个 promise 我可以使用。然后打印该值,但我无法将 function 的返回值分配给变量。

When calling a function that returns a Promise there are 2 ways to get the result from it:当调用返回 Promise 的Promise时,有两种方法可以从中获取结果:

  1. using .then使用.then
  2. using async/await使用异步/等待

.then approach: .then 方法:

convertFileToBase64(myFile)
  .then(result => {
    // do something with the result within this little function
  })
  .catch(err => {
    // handle any error
  });

async/await approach:异步/等待方法:

// 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM