使用AJAX时如何避免嵌套函数?
顺序异步调用很糟糕。有没有更具可读性的解决方案?
问题是这很难理解:
ajaxOne(function() {
// do something
ajaxTwo(function() {
// do something
ajaxThree()
});
});
匿名函数是在服务器响应时调用的回调。
我正在使用第三方 API 进行 AJAX 调用,因此我需要一个通用的解决方案。
Sequential Asynchronous calls are gross. Is there a more readable solution?
The problem is this is hard to follow:
ajaxOne(function() {
// do something
ajaxTwo(function() {
// do something
ajaxThree()
});
});
where the anonymous functions are callbacks that are called on server response.
I'm using a third party API to make the AJAX calls, so I need a generic solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的回调中不需要闭包范围(您可能不需要),您可以将回调放入单独的函数中并按其名称调用它们。喜欢:
If you don't need the closure scope in your callbacks, which you probably won't, you can just put the callbacks into separate functions and call them by their name. like:
函数式编程来拯救! jsdeferred 允许您像这样编写示例:
每个“顺序”ajaxOne/Two/Three 函数接收将其前任的返回结果作为参数。如果需要传递其他参数,可以在调用 ajax 链之前将它们公开在全局对象中。
functional programming to the rescue! jsdeferred lets you write your example like so:
each of the "sequential" ajaxOne/Two/Three functions receives the returned result of its predecessor as parameter. If you need to pass in additional parameters, you can expose them in a global object before you invoke your ajax chain.
如果您只有一个嵌套函数,则可以保持原样,但如果您有多个嵌套调用,则应考虑在单独的方法中编写这些回调,并从嵌套函数中调用它...
If you have only one nested function, it's Ok to leave it as is, but if you have several nested calls, you should consider writing these callbacks in a separate method, and calling it from the nested function...
首先我必须承认,我对 JavaScript 还比较陌生,但是我最近在使用 jQuery ajax 函数时遇到了同样的问题。我必须按照一定的顺序通过 POST 将几个文档上传到服务器。嵌套所有回调会产生完全混乱的代码。阅读答案后我思考了一个解决方案,并提出了一个对我来说效果很好的解决方案。它仅使用一个带有 switch 子句的函数来区分不同的回调调用:
如果这不是一个好主意,请告诉我。正如我所说,我不是 JavaScript 专家,但它对我来说效果很好。
最好的,
René
编辑:
过了一段时间我发现承诺 是解决这个问题的更好方法。
First I have to admit, I'm relatively new to JavaScript, but I recently encountered the same problem while using the jQuery ajax function. I had to upload a couple of documents via POST to a server in a certain order. Nesting all the call backs would have produced completely messed up code. I thought about a solution after reading the answers and came up with a solution that worked fine me. It uses only one function with a switch clause to differentiate the different callback invocations:
If this is not a good idea, please let me know. As I said, I'm not a JavaScript expert but I it worked pretty well for me.
Best,
René
Edit:
After a while I found out that Promises are a much better approach to solve this problem.