If promises and .then
are confusing, and you are somehow trying to get values out of the future to use in the here and now, consider async/await
, which allows you to write asynchronous code in a way which sorta kinda looks synchronous:
const canvas = await html2canvas(document.getElementById("chartContainer"));
const token = canvas.toDataURL("image/jpeg,1.0");
const img = { token };
console.log (img.token);
alert(img.token);
Internally, the above code is transpiled or interpreted in such as way as to wait for the html2canvas
promise to fulfill, using the equivalent of .then
. In other words, it ends up looking like this:
html2canvas(document.getElementById("chartContainer"))
.then(canvas => {
const token = canvas.toDataURL("image/jpeg,1.0");
const img = { token };
console.log (img.token);
alert(img.token);
});
Or, if you don't want to use async/await
for some reason, you could just write it like this to start with.
PS. Assuming the code above is inside a function, it would need to be an async function
.