正常的同步处理方式非常简单直接。希望对异步JavaScript代码和同步代码进行一些说明
- 函数接受输入。
- 该功能对这些输入执行操作。
- 该函数弹出一个值(返回一个值)。
- 该喷射可以被存储到一个变量中的值,直接在同步码的其他部分所使用的,等等
但异步似乎不能够做到这一点。
比方说,我有一个服务,我想出售。该服务的价格因地点而异。
我有一个用户:
- 输入邮编
- 邮编被发送到一个API,而返回城市名称。
- 我使用城市名称来运行返回价格的超级巨大函数。
- 我则想用价格在我同步代码的其他部分,而同步代码是超级长,在众多的功能,所有依赖于价格值跨越。
代码:
var calcPrice = function(city){
// stuff runs
return price;
};
// Async Function, taken from http://www.zippopotam.us/
// The "place name" is the city.
var returnLocationInfoByZip = function(zip, callback){
var client = new XMLHttpRequest();
var response;
client.open("GET", "http://api.zippopotam.us/us/" + zip, true);
client.onreadystatechange = function() {
if(client.readyState == 4) {
response = client.responseText;
callback(JSON.parse(response));
};
};
client.send();
};
var zip = "94043";
var price = returnLocationInfoByZip(zip, function(response){
calcPrice(response.places[0]["place name"]);
});
// This does not work. I'm going to call this the "dependent processing" part of my code.
functionThatDependsOnPrice(price);
AnotherFunctionThatDependsOnPrice(price);
MoreFunctionsThatDependsOnPrice(price);
EvenMoreFunctionsThatDependOnPrice(price);
// This I THINK would work instead
returnLocationInfoByZip(zip, function(response){
price = calcPrice(response.places[0]["place name"]);
functionThatDependsOnPrice(price);
AnotherFunctionThatDependsOnPrice(price);
MoreFunctionsThatDependsOnPrice(price);
EvenMoreFunctionsThatDependOnPrice(price);
});
馅都在回调代码是真的很丑陋和混乱。
我想在我的正常同步代码内使用价格变量。但calcPrice
的值永远不会返回,因此永远不会存储到变量的价格变量中。 calcPrice
的值永远卡在我的代码流的异步分支内,这迫使我在异步分支/回调中执行所有其他依赖处理。
那么几个问题:
它是正确的,异步代码是永远无法返回一个值回同步代码?正常的同步做事和思考事物的方式是行不通的。
脂肪回调是否非常正常?
我可以去无极路线,但如果我这样做,我只是馅所有依赖加工成我then
功能......这是一个有点清洁寻找,但它仍然是嵌套在内心深处,其他的事情。
http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – epascarello 2014-10-28 12:33:49
对我的三个问题,“是”,“是”和“是”? – fuzzybabybunny 2014-10-28 12:35:37