如何让bootbox.js弹窗等待用户操作后再执行后续脚本?
需求说明
当前函数处于复杂的JavaScript层级结构中,无法使用视图中的HTML代码(否则会丢失各脚本间传递的大量参数)。因需要密码掩码功能,选用bootbox.js实现弹窗,但现有代码在弹窗显示后会直接执行后续脚本,未等待用户操作的回调结果,希望实现类似原生JavaScript prompt的同步等待效果——用户完成弹窗操作后再执行后续代码。
当前不工作的Bootbox代码
function authorize() { alert("Script has started..."); var final_result = 0; bootbox.prompt({ title: "This is a prompt with a password input!", inputType: 'password', callback: function(result) { if (result!=null) { final_result = 1; } else { final_result = 0; } } }); alert("calling XYZ"); function xyz(); alert("Script has finished... final result is" + final_result); }
期望效果的原生JavaScript Prompt代码
function authorize() { alert("Script has started..."); var final_result = 0; let text = prompt("This is a prompt with a password input!", "") if (text!= null) { final_result = 1; } else { final_result = 0; } alert("calling xyz" ); function xyz(); alert("Script has finished... final result is" + final_result ); }
解决方案:用Promise+async/await实现同步风格代码
Bootbox本身是异步回调模式,无法直接改成同步阻塞,但可以通过Promise封装弹窗逻辑,配合async/await实现类似原生prompt的同步写法,同时保留原有参数传递逻辑。
修改后的代码如下:
// 把Bootbox密码弹窗封装为Promise function bootboxPasswordPrompt(title) { return new Promise((resolve) => { bootbox.prompt({ title: title, inputType: 'password', callback: function(result) { // 将用户操作结果传递给Promise的resolve resolve(result !== null ? 1 : 0); } }); }); } // 原函数改为async函数,使用await等待弹窗结果 async function authorize() { alert("Script has started..."); // 执行到此处会暂停,直到用户完成弹窗操作 var final_result = await bootboxPasswordPrompt("This is a prompt with a password input!"); alert("calling XYZ"); // 修正原代码的语法错误:此处应为调用函数而非定义 xyz(); alert("Script has finished... final result is" + final_result); } // 示例xyz函数定义 function xyz() { // 自定义业务逻辑 }
关键说明
- 用Promise包装Bootbox的弹窗逻辑,将回调结果通过
resolve传递,实现异步结果的标准化处理 - 标记
authorize为async函数,使用await等待Promise的执行结果,让代码执行流程在弹窗处暂停,直到用户操作完成 - 原代码中
function xyz();属于语法错误,修正为函数调用xyz();,若需定义函数需调整位置
内容的提问来源于stack exchange,提问作者Ashraf Sa4272
相关产品推荐
相关产品推荐

