如何链接ajax请求? [英] How to chain ajax requests?
本文介绍了如何链接ajax请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须与迫使我链接请求的远程 API 进行交互.这是异步模式下的回调地狱:
I have to interact with a remote api that forces me to chain requests. Thats a callback-hell in asynchronous mode:
// pseudocode: ajax(request_object, callback)
ajax(a, function() {
ajax(b(a.somedata), function() {
ajax(c(b.somedata), function() {
c.finish()
}
})
})
在同步模式下可读性更高:
It would be much more readable in sync mode:
sjax(a)
sjax(b(a.somedata))
sjax(c(b.somedata))
c.finish()
但是 Sjax 是邪恶的 :) 我如何以 nice 不那么邪恶和可读的方式做到这一点?
But Sjax is evil :) How do I do that in a nice not-so-evil and readable way?
推荐答案
不要使用匿名函数.给他们起名字.我不知道你是否能够做到我在下面写的:
Don't use anonymous functions. Give them names. I don't know if you're able to do what I wrote below though:
var step_3 = function() {
c.finish();
};
var step_2 = function(c, b) {
ajax(c(b.somedata), step_3);
};
var step_1 = function(b, a) {
ajax(b(a.somedata), step_2);
};
ajax(a, step_1);
这篇关于如何链接ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文