I have an issue where I need to run 2 method in the order it's being run.
Here is some sample code:
So I have these 2 sample methods:
part1() {
const element = document.getElementById("capture") as HTMLCanvasElement;
html2canvas(element).then((canvas) => {
this.thecanvas = canvas.toDataURL();
console.log('Dont do part2 until the.thecanvas is populated');
});
}
part2() {
// do other stuff but only after part1 is completed
console.log('All completed');
}
Im running it like this:
main() {
// I need them to run in this sequence
this.part(); // first
this.part2(); // last
}
I'm guessing Async/await?
How do I do this in Angular 12?
CodePudding user response:
Yes, you can use async/await
. This is how you change your code:
part1() {
const element = document.getElementById("capture") as HTMLCanvasElement;
return new Promise(async (resolve, reject) => {
try {
const canvas = await html2canvas(element)
this.thecanvas = canvas.toDataURL();
console.log('Dont do part2 until the.thecanvas is populated');
// when you complete the things successfully, you shoule call resolve else call reject
resolve('Dont do part2 until the.thecanvas is populated');
} catch (error) {
reject(error);
}
})
}
part2() {
// do other stuff but only after part1 is completed
return new Promise((resolve, reject) => {
console.log('All completed');
// when you complete the things successfully, you shoule call resolve else call reject
resolve('All completed');
})
}
You can always follow these steps when you have something async in nature. You can create a promise and you can resolve/reject
it based on the results.