我有一个弹出窗口,基本上是一个numpad,用户输入一些数字,它有一个按钮“完成”。
关于弹出窗口,我有两个函数(关于我的问题),我有一个激活函数和一个完成函数。
然后我有了第三个函数,它将onClick代码附加到一个按钮上,它处理numpad的激活,它还应该从numpad接收值。 问题是这些操作中的一个是瞬间的,另一个不是。 代码如下所示:
NumPad的功能:
Numpad: {
id: null,
type: null,
val: null,
BtnData: null,
activate: (element) => {
$("#btnTrigger").click();
Numpad.BtnData = element; //which button triggered the numpad
},
async done() {
return new Promise((resolve, reject) => {
// Some code to get the number into Numpad.val
resolve(Numpad.val)
});
},
}
在我的onclick函数中,我猜这就是问题所在:
$("#someIdSelector").click(async () => {
// This should execute as soon as the button is clicked and it does
Numpad.activate(document.getElementById("#someIdSelector"));
// This should execute only when Numpad.done() is resolved (when the user pressed done on the numpad)
SendData(name, await Numpad.done());
});
相反,onclick中的所有代码在我单击一个按钮后立即被执行,当然,此时numpad.done()是未定义的。 我还尝试了。then,但只要我按下一个按钮,console.log(“inside promise resolve”)就会被立即调用:
$("#someIdSelector").click(async () => {
// This should execute as soon as the button is clicked and it does
Numpad.activate(document.getElementById("#someIdSelector"));
// This should execute only when Numpad.done() is resolved (when the user pressed done on the numpad)
Numpad.done().then((data) => {
console.log("Inside promise resolve");
SendData(name, data);
});
});
当您将一个方法声明为async
时,一旦命中第一个await
,它将隐式地返回一个promise
。
您的done
方法不包含任何await
语句,因此它立即返回一个已经解析的promise
,其结果是未解析的promise
。
如果手动返回promise
,请删除async
关键字; 这样,当等待numpad.done()
时,您将等待promise
。