gpt4 book ai didi

Javascript MVC 应用程序 - 使用回调编码 "while"条件

转载 作者:行者123 更新时间:2023-11-30 17:37:14 25 4
gpt4 key购买 nike

我正在努力寻找一种很好的逻辑方式来使用异步调用在 javascript 中表示此伪代码:

这是 Controller 伪代码:

// get the data for the main page, server will return login details if not logged in
model.getdata(mypage);

// keep trying to get a login until the user successfully logs in
while (model.loggedin() === false)
{
// show the login form
view.showloginform(model.data);
// and push that login to the server
model.trylogin(view.login.userdata);
if (!model.loggedin()) // show the error to the user and they will click ok
view.showloginerrordetails(model.loginresponse);
else // try to get the main page data again
model.getdata(mypage);
}

// now we are logged in so we can show the main page
view.showmainpage(model.data);

model.getdata is async while waiting for the server to respond view.showloginform is async while waiting for the user to fill the form in model.trylogin will be async while waiting for the server. etc

很明显,如果任何调用是异步的,我的循环将无法工作。他们都是

我认为当循环只发生一次时使用闭包很容易,但是当循环可以运行多次迭代时,你如何将所有这些写在一个函数中?

这只是一个简单的示例,但我想支持使用相同想法的更复杂的工作流。

我对人们如何在 javascript 中构建这样的代码非常感兴趣,这样代码才具有可读性和优雅性等等。

最佳答案

// capture form submit
function submit(callback) {
//create ajax request and post to server
};

function callback(result) {
// inspect result
if (result.valid) {
//do cool logged in stuff
} else {
//display whatever the error was
}
}

由于您使用的是 asp.net MVC,因此您还可以绑定(bind) View 中的字段,以便它们显示任何错误。这样你就不需要使用 javascript 只需将登录表单直接发布到服务器并在那里进行验证和重定向。做这样的结帐 ASP.NET MVC: Custom Validation by DataAnnotationhttp://msdn.microsoft.com/en-us/library/ee256141(v=vs.100).aspx

关于Javascript MVC 应用程序 - 使用回调编码 "while"条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21788012/

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