本文介绍了如何链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 的是邪恶的:)我怎么做,在一个不那么邪恶和可读的方式?
But Sjax is evil :) How do I do that in a 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请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!