我在javascript中有一个函数可以运行另一个函数,它应该等待被调用函数完成其执行并将控制权返回给调用函数。但是,这不会发生,并且在被调用函数开始执行后,调用函数不会等待并完全通过。
function ButtonClick() {
AskQuestion(param1, param2, function (success) {
if (success == true) {
//do some staff here
}
}
}
function AskQuestion(param1, param2) {
//here I present a dialog box and ask users to fill it out, then I
//validate their entry. If it's validated then I do: `return true` and
//if it's not: `return false`
}
在我调用AskQuestion函数之后,它不会等待,success
将始终为FALSE
我在这里做什么错了?
答案 0 :(得分:2)
要将回调传递给AskQuestion,该函数必须接受回调,并在完成异步任务后实际上将其回调:
function ButtonClick() {
AskQuestion(param1, param2, function (success) { // This anonymous function will be called at the end of the AskQuestion execution
if (success == true) {
//do some staff here
}
});
}
function AskQuestion(param1, param2, callback) {
//here I present a dialog box and ask users to fill it out, then I
//validate their entry. If it's validated then I do: `return true` and
//if it's not: `return false`
callback(success); // assuming success is a variable set to true if no problem happened
}
答案 1 :(得分:0)
正如Gregory指出的那样,您可能应该在代码中的某处调用回调,以传递所需结果的结果,然后在回调中对其进行处理。
但这取决于您用来显示对话框的内容。 例如,window.prompt()停止执行JavaScript,直到用户给出反馈为止。
{
"parse": "full",
"text": "http://example.com/file1.png",
"attachments":[
{
"image_url": "http://example.com/file1.png"
}
],
"unfurl_media":true,
"unfurl_links":true
}
仅在提交提示后才打印名称。