gpt4 book ai didi

javascript - Angular 2 中的异步等待

转载 作者:行者123 更新时间:2023-12-04 14:53:58 26 4
gpt4 key购买 nike

在这个例子之后,我对 Angular 2 中的 await/async 有了基本的了解:

 async getValueWithAsync() {
const value = <number>await this.resolveAfter2Seconds(20);
console.log(`async result: ${value}`);
}

在我的 Angular 应用程序中,我需要截取一个 div 的屏幕截图,将其转换为 Blob,从我的后端获取一个 Amazon 预签名的 URL,并使用预签名的 URL 上传屏幕截图客户端。

我的逻辑的每个部分都在 PostMan 上工作和测试。我的问题是图片在创建它的函数返回之前上传,导致上传的图片为空。

 async generateAnswer() {
// takes a snaphot of the div and returns it as Blob
var pic = await this.getPicture()
// coonects to the backend and returns an Amazon S3 presigned Url
this.s3Upload.getPresignedUrl("myPic")
.subscribe(r => {
// upload the snapshot as a Blob to my bucket
this.s3Upload.uploadFile(r["url"], pic)
.subscribe(r => console.log("uploaded"))
})
}

getPicture() {
// takes a snaphot of the div and returns it as Blob
return this.slideGenerator.generateAnswer()
}

我的 generateAnswer():

generateAnswer() {
let answer = document.querySelector('#answer') as HTMLImageElement;
html2canvas(answer, { useCORS: true }).then(canvas => {
var base64image = canvas.toDataURL("image/png");
this.blobImage = this.dataURIToBlob(base64image);
return (this.blobImage);
});
}

当我记录图片时,我得到 undefined此逻辑不起作用,因为它不等待 this.getPicture() 在加载之前返回一个值。

最佳答案

你只能在异步函数中使用 await,你应该把 await 放在你希望同步运行的任何东西之前(先完成执行)

async generateAnswer() {
const answer = document.querySelector('#answer') as HTMLImageElement;
const canvas = await html2canvas(answer, { useCORS: true });
const base64image = canvas.toDataURL("image/png");
this.blobImage = this.dataURIToBlob(base64image);//use await if async
return this.blobImage;
}

还有一件事,避免在不需要时使用 varlet :)

关于javascript - Angular 2 中的异步等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68508128/

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