gpt4 book ai didi

angular - 等待异步函数返回 Typescript 中的值。

转载 作者:行者123 更新时间:2023-12-02 20:36:29 25 4
gpt4 key购买 nike

我有一个函数 (Function1),它调用另一个返回字符串的函数 (Function2)。

我希望Function1调用Function2,但是等待并获取Function2的返回值。你打算怎样做呢?这是我的代码(未按预期工作):

这是我的函数1:

async Function1() {
const message = await this.dialogButtonPress();
alert(message);
}

这是我的函数2:

async dialogButtonPress() : Promise<string> {
const doneButtonPromise = new Promise((resolve) => {
const doneButton = document.getElementById("done-button");
const resolver = () => {
resolve();
doneButton.removeEventListener("click", resolver);
}
doneButton.addEventListener("click", resolver);
});

const cancelButtonPromise = new Promise((resolve) => {
const cancelButton = document.getElementById("cancel-button");
const resolver = () => {
resolve();
cancelButton.removeEventListener("click", resolver);
}
cancelButton.addEventListener("click", resolver);
})

doneButtonPromise.then(() => {
console.log("DONE BUTTON PRESSED!");
return "Confirm";

});

cancelButtonPromise.then(() => {
console.log("CANCEL BUTTON PRESSED!");
return "Cancel";
});
}

最佳答案

如果您使用 Promise.race 作为 other answer建议,您不会清理未按下的按钮的事件处理程序。您将仅清理按下的按钮的处理程序。如果是我,我只会组合事件处理程序,以确保按下任何按钮时所有内容都会被清理:

async dialogButtonPress(): Promise<string> {
return new Promise<string>((resolve) => {
const doneButton = document.getElementById("done-button")!;
const cancelButton = document.getElementById("cancel-button")!;
const resolver = (ev: Event) => {
doneButton.removeEventListener("click", resolver);
cancelButton.removeEventListener("click", resolver);
// This is where we determine which button was clicked.
resolve(ev.target === doneButton ? "Confirm" : "Cancel");
}
doneButton.addEventListener("click", resolver);
cancelButton.addEventListener("click", resolver);
});
}

它可以扩展到任意数量的按钮:

async dialogButtonPress(): Promise<string> {
return new Promise<string>((resolve) => {
// You just need to expand this map in order to support additional buttons.
const idToResponse: Record<string, string> = {
"done-button": "Confirm",
"cancel-button": "Cancel",
};
const buttons = Object.keys(idToResponse).map((id) => document.getElementById(id)!);
const resolver = (ev: MouseEvent) => {
for (const button of buttons) {
button.removeEventListener("click", resolver);
}
// We index into idToResponse to convert the button's id to a specific response.
resolve(idToResponse[(ev.target as Element).id]);
}

for (const button of buttons) {
button.addEventListener("click", resolver);
}
});
}

关于angular - 等待异步函数返回 Typescript 中的值。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46962665/

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