我有一個問題,我需要按照它運行的順序運行 2 個方法。
下面是一些示例代碼:
所以我有這兩個示例方法:
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');
}
我像這樣運行它:
main() {
// I need them to run in this sequence
this.part(); // first
this.part2(); // last
}
我正在猜測 Async/await?
我如何在 Angular 12 中做到這一點?
uj5u.com熱心網友回復:
是的,您可以使用async/await. 這是您更改代碼的方式:
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');
})
}
當你有一些異步的東西時,你總是可以遵循這些步驟。你可以創建一個承諾,你可以resolve/reject根據結果來創建它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/335764.html
