This question already has an answer here:
这个问题已经有了答案:
- How do I return the response from an asynchronous call? 33 answers
- 如何从异步调用返回响应?33个答案
I have something like this, where it is a simple call to a script that gives me back a value, a string..
我有这样的东西,它是对脚本的一个简单调用,返回一个值,一个字符串。
function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {
return data;
}
});
}
but if I call something like this
但如果我这样称呼
var output = testAjax(svar); // output will be undefined...
so how can I return the value? the below code does not seem to work either...
那么如何返回值呢?下面的代码似乎也不起作用……
function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {
}
});
return data;
}
5 个解决方案
#1
319
The only way to return the data from the function would be to make a synchronous call instead of an asynchronous call, but that would freeze up the browser while it's waiting for the response.
从函数返回数据的唯一方法是进行同步调用,而不是异步调用,但这会在浏览器等待响应时冻结浏览器。
You can pass in a callback function that handles the result:
您可以传入一个回调函数来处理结果:
function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
success:function(data) {
handleData(data);
}
});
}
Call it like this:
叫它是这样的:
testAjax(function(output){
// here you use the output
});
// Note: the call won't wait for the result,
// so it will continue with the code here while waiting.
#2
343
Note: This answer was written in February 2010.
See updates from 2015, 2016 and 2017 at the bottom.
注:这个答案写于2010年2月。从2015年、2016年和2017年的底部看更新。
You can't return anything from a function that is asynchronous. What you can return is a promise. I explained how promises work in jQuery in my answers to those questions:
你不能从一个异步的函数返回任何东西。你能回报的是一个承诺。在回答这些问题时,我解释了如何使用jQuery来实现承诺:
- JavaScript function that returns AJAX call data
- 返回AJAX调用数据的JavaScript函数
- jQuery jqXHR - cancel chained calls, trigger error chain
- jQuery jqXHR -取消链式调用,触发错误链。
If you could explain why do you want to return the data and what do you want to do with it later, then I might be able to give you a more specific answer how to do it.
如果你能解释为什么你想要返回数据以及你以后想做什么,那么我也许能给你一个更具体的答案。
Generally, instead of:
一般来说,而不是:
function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {
return data;
}
});
}
you can write your testAjax function like this:
你可以这样写你的testAjax函数:
function testAjax() {
return $.ajax({
url: "getvalue.php"
});
}
Then you can get your promise like this:
然后你就可以得到这样的承诺:
var promise = testAjax();
You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this:
你可以存储你的承诺,你可以传递它,你可以在函数调用中使用它作为参数你可以从函数中返回它,但是当你最终想要使用AJAX调用返回的数据时,你必须这样做:
promise.success(function (data) {
alert(data);
});
(See updates below for simplified syntax.)
(请参阅下面的更新以了解简化的语法。)
If your data is available at this point then this function will be invoked immediately. If it isn't then it will be invoked as soon as the data is available.
如果此时您的数据可用,那么将立即调用此函数。如果不是,那么在数据可用时就会调用它。
The whole point of doing all of this is that your data is not available immediately after the call to $.ajax because it is asynchronous. Promises is a nice abstraction for functions to say: I can't return you the data because I don't have it yet and I don't want to block and make you wait so here's a promise instead and you'll be able to use it later, or to just give it to someone else and be done with it.
所有这些操作的全部意义在于,在调用$之后,您的数据不能立即使用。因为它是异步的。承诺是一个很好的抽象函数的说:我不能回报你的数据,因为我没有它,我不想阻止,让你等待这是一个承诺,你将能够使用它之后,或者只是给别人做。
See this DEMO.
看到这个演示。
UPDATE (2015)
Currently (as of March, 2015) jQuery Promises are not compatible with the Promises/A+ specification which means that they may not cooperate very well with other Promises/A+ conformant implementations.
目前(截至2015年3月)jQuery承诺与promise /A+规范不兼容,这意味着它们可能无法与其他promise /A+一致性实现很好地配合。
However jQuery Promises in the upcoming version 3.x will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out). Currently (as of May, 2015) the stable versions of jQuery are 1.x and 2.x.
但是jQuery在即将发布的版本3中承诺。x将与promise /A+规范兼容(感谢Benjamin Gruenbaum指出这一点)。目前(截止2015年5月)jQuery稳定版为1。倍和2.倍。
What I explained above (in March, 2011) is a way to use jQuery Deferred Objects to do something asynchronously that in synchronous code would be achieved by returning a value.
我在上面(2011年3月)所解释的是一种使用jQuery递延对象来异步完成一些事情的方法,在同步代码中,通过返回一个值就可以实现这些事情。
But a synchronous function call can do two things - it can either return a value (if it can) or throw an exception (if it can't return a value). Promises/A+ addresses both of those use cases in a way that is pretty much as powerful as exception handling in synchronous code. The jQuery version handles the equivalent of returning a value just fine but the equivalent of complex exception handling is somewhat problematic.
但是同步函数调用可以做两件事——它可以返回一个值(如果可以),也可以抛出一个异常(如果不能返回一个值)。promise /A+处理这两个用例的方式与同步代码中的异常处理一样强大。jQuery版本可以很好地处理返回值的等效项,但是复杂异常处理的等效项有点问题。
In particular, the whole point of exception handling in synchronous code is not just giving up with a nice message, but trying to fix the problem and continue the execution, or possibly rethrowing the same or a different exception for some other parts of the program to handle. In synchronous code you have a call stack. In asynchronous call you don't and advanced exception handling inside of your promises as required by the Promises/A+ specification can really help you write code that will handle errors and exceptions in a meaningful way even for complex use cases.
特别地,在同步代码中异常处理的整个要点不仅仅是放弃一条漂亮的消息,而是试图修复问题并继续执行,或者可能为程序的其他部分重新抛出相同或不同的异常。在同步代码中,您有一个调用堆栈。在异步调用中,您不需要这样做,并且根据promise /A+规范的要求,在promise内部进行高级异常处理,这可以帮助您编写代码,即使是在复杂的用例中,也可以以一种有意义的方式处理错误和异常。
For differences between jQuery and other implementations, and how to convert jQuery promises to Promises/A+ compliant, see Coming from jQuery by Kris Kowal et al. on the Q library wiki and Promises arrive in JavaScript by Jake Archibald on HTML5 Rocks.
关于jQuery和其他实现之间的差异,以及如何将jQuery转换成承诺/A+兼容的,请参见Kris Kowal等人在Q库wiki上的jQuery,以及Jake Archibald在HTML5 Rocks上的JavaScript承诺。
How to return a real promise
The function from my example above:
上面我的例子中的函数:
function testAjax() {
return $.ajax({
url: "getvalue.php"
});
}
returns a jqXHR object, which is a jQuery Deferred Object.
返回jqXHR对象,它是一个jQuery延迟对象。
To make it return a real promise, you can change it to - using the method from the Q wiki:
为了让它返回一个真正的承诺,你可以用Q wiki的方法来改变它。
function testAjax() {
return Q($.ajax({
url: "getvalue.php"
}));
}
or, using the method from the HTML5 Rocks article:
或者,使用HTML5 Rocks文章中的方法:
function testAjax() {
return Promise.resolve($.ajax({
url: "getvalue.php"
}));
}
This Promise.resolve($.ajax(...))
is also what is explained in the promise
module documentation and it should work with ES6 Promise.resolve()
.
这个承诺.resolve($.ajax(…))也是promise模块文档中所解释的,它应该与ES6 promisee .resolve()一起工作。
To use the ES6 Promises today you can use es6-promise module's polyfill()
by Jake Archibald.
要使用今天的ES6承诺,您可以使用Jake Archibald的ES6承诺模块的polyfill()。
To see where you can use the ES6 Promises without the polyfill, see: Can I use: Promises.
要查看在哪里可以使用没有polyfill的ES6承诺,请参见:can I use: promise。
For more info see:
更多信息见:
- http://bugs.jquery.com/ticket/14510
- http://bugs.jquery.com/ticket/14510
- https://github.com/jquery/jquery/issues/1722
- https://github.com/jquery/jquery/issues/1722
- https://gist.github.com/domenic/3889970
- https://gist.github.com/domenic/3889970
- http://promises-aplus.github.io/promises-spec/
- http://promises-aplus.github.io/promises-spec/
- http://www.html5rocks.com/en/tutorials/es6/promises/
- http://www.html5rocks.com/en/tutorials/es6/promises/
Future of jQuery
Future versions of jQuery (starting from 3.x - current stable versions as of May 2015 are 1.x and 2.x) will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out in the comments). "Two changes that we've already decided upon are Promise/A+ compatibility for our Deferred implementation [...]" (jQuery 3.0 and the future of Web development). For more info see: jQuery 3.0: The Next Generations by Dave Methvin and jQuery 3.0: More interoperability, less Internet Explorer by Paul Krill.
jQuery的未来版本(从3开始)。x -截至2015年5月的当前稳定版本为1。x和2.x)将与promise /A+规范兼容(感谢Benjamin Gruenbaum在评论中指出这一点)。“我们已经决定的两个变化是承诺/A+兼容我们的延迟实现[……]”(jQuery 3.0与Web开发的未来)更多信息请参见:jQuery 3.0: Dave Methvin和jQuery 3.0:更多的互操作性,更少的Internet Explorer由Paul Krill编写。
Interesting talks
- Boom, Promises/A+ Was Born by Domenic Denicola (JSConfUS 2013)
- Boom, promise /A+诞生于Domenic Denicola (JSConfUS 2013)
- Redemption from Callback Hell by Michael Jackson and Domenic Denicola (HTML5DevConf 2013)
- 迈克尔·杰克逊和多梅尼克拉的《从回调地狱的救赎》(HTML5DevConf 2013)
- JavaScript Promises by David M. Lee (Nodevember 2014)
- David M. Lee的JavaScript承诺(Nodevember 2014)
UPDATE (2016)
There is a new syntax in ECMA-262, 6th Edition, Section 14.2 called arrow functions that may be used to further simplify the examples above.
在第6版的ECMA-262中有一种新的语法,叫做箭头函数,可以用来进一步简化上面的示例。
Using the jQuery API, instead of:
使用jQuery API,而不是:
promise.success(function (data) {
alert(data);
});
you can write:
你可以写:
promise.success(data => alert(data));
or using the Promises/A+ API:
或使用promise /A+ API:
promise.then(data => alert(data));
Remember to always use rejection handlers either with:
记住一定要使用拒绝处理程序:
promise.then(data => alert(data), error => alert(error));
or with:
或:
promise.then(data => alert(data)).catch(error => alert(error));
See this answer to see why you should always use rejection handlers with promises:
请查看此答案,以了解为什么您应该始终使用带有承诺的拒绝处理程序:
- Should I refrain from handling Promise rejection asynchronously?
- 我应该避免异步地处理承诺拒绝吗?
Of course in this example you could use just promise.then(alert)
because you're just calling alert
with the same arguments as your callback, but the arrow syntax is more general and lets you write things like:
当然,在这个例子中,你可以使用promisethen (alert)因为你调用alert的参数和回调的参数相同,但是箭头语法更一般,你可以这样写:
promise.then(data => alert("x is " + data.x));
Not every browser supports this syntax yet, but there are certain cases when you're sure what browser your code will run on - e.g. when writing a Chrome extension, a Firefox Add-on, or a desktop application using Electron, NW.js or AppJS (see this answer for details).
并不是所有的浏览器都支持这种语法,但是在某些情况下,当你确定你的代码将运行在哪个浏览器上时——例如,当你编写Chrome扩展、Firefox扩展或使用电子的桌面应用程序时。js或AppJS(详细信息请参见此答案)。
For the support of arrow functions, see:
箭头函数的支持,见:
- http://caniuse.com/#feat=arrow-functions
- = arrow-functions http://caniuse.com/壮举
- http://kangax.github.io/compat-table/es6/#test-arrow_functions
- http://kangax.github.io/compat-table/es6/ test-arrow_functions
UPDATE (2017)
There is an even newer syntax right now called async functions with a new await
keyword that instead of this code:
现在有一种更新的语法叫做异步函数,它有一个新的wait关键字而不是这个代码:
functionReturningPromise()
.then(data => console.log('Data:', data))
.catch(error => console.log('Error:', error));
lets you write:
让你写:
try {
let data = await functionReturningPromise();
console.log('Data:', data);
} catch (error) {
console.log('Error:', error);
}
You can only use it inside of a function created with the async
keyword. For more info, see:
您只能在用async关键字创建的函数中使用它。更多信息,请参见:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
For support in browsers, see:
对于浏览器中的支持,请参见:
- http://caniuse.com/async-functions
- http://caniuse.com/async-functions
For support in Node, see:
对于节点内的支持,请参见:
- http://node.green/#ES2017-features-async-functions
- http://node.green/ ES2017-features-async-functions
In places where you don't have native support for async
and await
you can use Babel:
在没有异步本地支持的地方,您可以使用Babel:
- https://babeljs.io/docs/plugins/transform-async-to-generator/
- https://babeljs.io/docs/plugins/transform-async-to-generator/
or with a slightly different syntax a generator based approach like in co
or Bluebird coroutines:
或者使用稍微不同的语法,基于生成器的方法,比如co或Bluebird coroutines:
- https://www.npmjs.com/package/co
- https://www.npmjs.com/package/co
- http://bluebirdjs.com/docs/api/promise.coroutine.html
- http://bluebirdjs.com/docs/api/promise.coroutine.html
More info
Some other questions about promises for more details:
关于承诺更多细节的其他问题:
- promise call separate from promise-resolution
- 承诺召唤与承诺决定分开
- Q Promise delay
- 问承诺延迟
- Return Promise result instead of Promise
- 回报承诺,而不是承诺
- Exporting module from promise result
- 从承诺结果导出模块
- What is wrong with promise resolving?
- 承诺解决有什么问题?
- Return value in function from a promise block
- 从承诺块返回函数值
- How can i return status inside the promise?
- 如何在承诺中返回状态?
- Should I refrain from handling Promise rejection asynchronously?
- 我应该避免异步地处理承诺拒绝吗?
- Is the deferred/promise concept in JavaScript a new one or is it a traditional part of functional programming?
- JavaScript中的延迟/承诺概念是新概念还是函数式编程的传统部分?
- How can I chain these functions together with promises?
- 如何将这些函数和承诺联系起来?
- Promise.all in JavaScript: How to get resolve value for all promises?
- 的承诺。JavaScript:如何获得所有承诺的解析值?
- Why Promise.all is undefined
- 为什么承诺。都是未定义的
- function will return null from javascript post/get
- 函数将从javascript post/get返回null
- Use cancel() inside a then-chain created by promisifyAll
- 在promisifyAll创建的then-chain中使用cancel()
- Why is it possible to pass in a non-function parameter to Promise.then() without causing an error?
- 为什么可以将非函数参数传递给promisethen()而不会导致错误?
- Implement promises pattern
- 实现承诺模式
- Promises and performance
- 承诺和性能
- Trouble scraping two URLs with promises
- 用承诺抓取两个url有困难
- http.request not returning data even after specifying return on the 'end' event
- http。即使在指定“结束”事件的返回之后,也不要返回数据
- async.each not iterating when using promises
- 异步。当使用承诺时,每个都不重复
- jQuery jqXHR - cancel chained calls, trigger error chain
- jQuery jqXHR -取消链式调用,触发错误链。
- Correct way of handling promisses and server response
- 正确处理承诺和服务器响应的方式
- Return a value from a function call before completing all operations within the function itself?
- 在完成函数本身中的所有操作之前,从函数调用返回一个值?
- Resolving a setTimeout inside API endpoint
- 解决API端点内部的setTimeout
- Async wait for a function
- 异步等待一个函数
- JavaScript function that returns AJAX call data
- 返回AJAX调用数据的JavaScript函数
- try/catch blocks with async/await
- 与异步/等待try / catch块
- jQuery Deferred not calling the resolve/done callbacks in order
- jQuery没有按顺序调用解析/完成的回调
- Returning data from ajax results in strange object
- 从ajax返回数据会产生奇怪的对象
- javascript - Why is there a spec for sync and async modules?
- 为什么有一个用于同步和异步模块的规范?
#3
146
you can add async option to false and return outside the ajax call.
您可以将async选项添加到false,并在ajax调用之外返回。
function testAjax() {
var result="";
$.ajax({
url:"getvalue.php",
async: false,
success:function(data) {
result = data;
}
});
return result;
}
#4
0
Idk if you guys solved it but I recommend another way to do it, and it works :)
Idk,如果你们解出来了但我推荐另一种方法,它是有效的
ServiceUtil = ig.Class.extend({
base_url : 'someurl',
sendRequest: function(request)
{
var url = this.base_url + request;
var requestVar = new XMLHttpRequest();
dataGet = false;
$.ajax({
url: url,
async: false,
type: "get",
success: function(data){
ServiceUtil.objDataReturned = data;
}
});
return ServiceUtil.objDataReturned;
}
})
So the main idea here is that, by adding async: false, then you make everything waits until the data is retrieved. Then you assign it to a static variable of the class, and everything magically works :)
这里的主要思想是,通过添加async: false,您可以让所有的东西都等待,直到数据被检索。然后将其赋值给类的静态变量,然后一切魔术般地工作:)
#5
-10
See jquery docs example: http://api.jquery.com/jQuery.ajax/ (about 2/3 the page)
参见jquery文档示例:http://api.jquery.com/jQuery.ajax/(大约2/3页)
You may be looking for following code:
您可能正在寻找以下代码:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Same page...lower down.
同一页面…低下来。
#1
319
The only way to return the data from the function would be to make a synchronous call instead of an asynchronous call, but that would freeze up the browser while it's waiting for the response.
从函数返回数据的唯一方法是进行同步调用,而不是异步调用,但这会在浏览器等待响应时冻结浏览器。
You can pass in a callback function that handles the result:
您可以传入一个回调函数来处理结果:
function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
success:function(data) {
handleData(data);
}
});
}
Call it like this:
叫它是这样的:
testAjax(function(output){
// here you use the output
});
// Note: the call won't wait for the result,
// so it will continue with the code here while waiting.
#2
343
Note: This answer was written in February 2010.
See updates from 2015, 2016 and 2017 at the bottom.
注:这个答案写于2010年2月。从2015年、2016年和2017年的底部看更新。
You can't return anything from a function that is asynchronous. What you can return is a promise. I explained how promises work in jQuery in my answers to those questions:
你不能从一个异步的函数返回任何东西。你能回报的是一个承诺。在回答这些问题时,我解释了如何使用jQuery来实现承诺:
- JavaScript function that returns AJAX call data
- 返回AJAX调用数据的JavaScript函数
- jQuery jqXHR - cancel chained calls, trigger error chain
- jQuery jqXHR -取消链式调用,触发错误链。
If you could explain why do you want to return the data and what do you want to do with it later, then I might be able to give you a more specific answer how to do it.
如果你能解释为什么你想要返回数据以及你以后想做什么,那么我也许能给你一个更具体的答案。
Generally, instead of:
一般来说,而不是:
function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {
return data;
}
});
}
you can write your testAjax function like this:
你可以这样写你的testAjax函数:
function testAjax() {
return $.ajax({
url: "getvalue.php"
});
}
Then you can get your promise like this:
然后你就可以得到这样的承诺:
var promise = testAjax();
You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this:
你可以存储你的承诺,你可以传递它,你可以在函数调用中使用它作为参数你可以从函数中返回它,但是当你最终想要使用AJAX调用返回的数据时,你必须这样做:
promise.success(function (data) {
alert(data);
});
(See updates below for simplified syntax.)
(请参阅下面的更新以了解简化的语法。)
If your data is available at this point then this function will be invoked immediately. If it isn't then it will be invoked as soon as the data is available.
如果此时您的数据可用,那么将立即调用此函数。如果不是,那么在数据可用时就会调用它。
The whole point of doing all of this is that your data is not available immediately after the call to $.ajax because it is asynchronous. Promises is a nice abstraction for functions to say: I can't return you the data because I don't have it yet and I don't want to block and make you wait so here's a promise instead and you'll be able to use it later, or to just give it to someone else and be done with it.
所有这些操作的全部意义在于,在调用$之后,您的数据不能立即使用。因为它是异步的。承诺是一个很好的抽象函数的说:我不能回报你的数据,因为我没有它,我不想阻止,让你等待这是一个承诺,你将能够使用它之后,或者只是给别人做。
See this DEMO.
看到这个演示。
UPDATE (2015)
Currently (as of March, 2015) jQuery Promises are not compatible with the Promises/A+ specification which means that they may not cooperate very well with other Promises/A+ conformant implementations.
目前(截至2015年3月)jQuery承诺与promise /A+规范不兼容,这意味着它们可能无法与其他promise /A+一致性实现很好地配合。
However jQuery Promises in the upcoming version 3.x will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out). Currently (as of May, 2015) the stable versions of jQuery are 1.x and 2.x.
但是jQuery在即将发布的版本3中承诺。x将与promise /A+规范兼容(感谢Benjamin Gruenbaum指出这一点)。目前(截止2015年5月)jQuery稳定版为1。倍和2.倍。
What I explained above (in March, 2011) is a way to use jQuery Deferred Objects to do something asynchronously that in synchronous code would be achieved by returning a value.
我在上面(2011年3月)所解释的是一种使用jQuery递延对象来异步完成一些事情的方法,在同步代码中,通过返回一个值就可以实现这些事情。
But a synchronous function call can do two things - it can either return a value (if it can) or throw an exception (if it can't return a value). Promises/A+ addresses both of those use cases in a way that is pretty much as powerful as exception handling in synchronous code. The jQuery version handles the equivalent of returning a value just fine but the equivalent of complex exception handling is somewhat problematic.
但是同步函数调用可以做两件事——它可以返回一个值(如果可以),也可以抛出一个异常(如果不能返回一个值)。promise /A+处理这两个用例的方式与同步代码中的异常处理一样强大。jQuery版本可以很好地处理返回值的等效项,但是复杂异常处理的等效项有点问题。
In particular, the whole point of exception handling in synchronous code is not just giving up with a nice message, but trying to fix the problem and continue the execution, or possibly rethrowing the same or a different exception for some other parts of the program to handle. In synchronous code you have a call stack. In asynchronous call you don't and advanced exception handling inside of your promises as required by the Promises/A+ specification can really help you write code that will handle errors and exceptions in a meaningful way even for complex use cases.
特别地,在同步代码中异常处理的整个要点不仅仅是放弃一条漂亮的消息,而是试图修复问题并继续执行,或者可能为程序的其他部分重新抛出相同或不同的异常。在同步代码中,您有一个调用堆栈。在异步调用中,您不需要这样做,并且根据promise /A+规范的要求,在promise内部进行高级异常处理,这可以帮助您编写代码,即使是在复杂的用例中,也可以以一种有意义的方式处理错误和异常。
For differences between jQuery and other implementations, and how to convert jQuery promises to Promises/A+ compliant, see Coming from jQuery by Kris Kowal et al. on the Q library wiki and Promises arrive in JavaScript by Jake Archibald on HTML5 Rocks.
关于jQuery和其他实现之间的差异,以及如何将jQuery转换成承诺/A+兼容的,请参见Kris Kowal等人在Q库wiki上的jQuery,以及Jake Archibald在HTML5 Rocks上的JavaScript承诺。
How to return a real promise
The function from my example above:
上面我的例子中的函数:
function testAjax() {
return $.ajax({
url: "getvalue.php"
});
}
returns a jqXHR object, which is a jQuery Deferred Object.
返回jqXHR对象,它是一个jQuery延迟对象。
To make it return a real promise, you can change it to - using the method from the Q wiki:
为了让它返回一个真正的承诺,你可以用Q wiki的方法来改变它。
function testAjax() {
return Q($.ajax({
url: "getvalue.php"
}));
}
or, using the method from the HTML5 Rocks article:
或者,使用HTML5 Rocks文章中的方法:
function testAjax() {
return Promise.resolve($.ajax({
url: "getvalue.php"
}));
}
This Promise.resolve($.ajax(...))
is also what is explained in the promise
module documentation and it should work with ES6 Promise.resolve()
.
这个承诺.resolve($.ajax(…))也是promise模块文档中所解释的,它应该与ES6 promisee .resolve()一起工作。
To use the ES6 Promises today you can use es6-promise module's polyfill()
by Jake Archibald.
要使用今天的ES6承诺,您可以使用Jake Archibald的ES6承诺模块的polyfill()。
To see where you can use the ES6 Promises without the polyfill, see: Can I use: Promises.
要查看在哪里可以使用没有polyfill的ES6承诺,请参见:can I use: promise。
For more info see:
更多信息见:
- http://bugs.jquery.com/ticket/14510
- http://bugs.jquery.com/ticket/14510
- https://github.com/jquery/jquery/issues/1722
- https://github.com/jquery/jquery/issues/1722
- https://gist.github.com/domenic/3889970
- https://gist.github.com/domenic/3889970
- http://promises-aplus.github.io/promises-spec/
- http://promises-aplus.github.io/promises-spec/
- http://www.html5rocks.com/en/tutorials/es6/promises/
- http://www.html5rocks.com/en/tutorials/es6/promises/
Future of jQuery
Future versions of jQuery (starting from 3.x - current stable versions as of May 2015 are 1.x and 2.x) will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out in the comments). "Two changes that we've already decided upon are Promise/A+ compatibility for our Deferred implementation [...]" (jQuery 3.0 and the future of Web development). For more info see: jQuery 3.0: The Next Generations by Dave Methvin and jQuery 3.0: More interoperability, less Internet Explorer by Paul Krill.
jQuery的未来版本(从3开始)。x -截至2015年5月的当前稳定版本为1。x和2.x)将与promise /A+规范兼容(感谢Benjamin Gruenbaum在评论中指出这一点)。“我们已经决定的两个变化是承诺/A+兼容我们的延迟实现[……]”(jQuery 3.0与Web开发的未来)更多信息请参见:jQuery 3.0: Dave Methvin和jQuery 3.0:更多的互操作性,更少的Internet Explorer由Paul Krill编写。
Interesting talks
- Boom, Promises/A+ Was Born by Domenic Denicola (JSConfUS 2013)
- Boom, promise /A+诞生于Domenic Denicola (JSConfUS 2013)
- Redemption from Callback Hell by Michael Jackson and Domenic Denicola (HTML5DevConf 2013)
- 迈克尔·杰克逊和多梅尼克拉的《从回调地狱的救赎》(HTML5DevConf 2013)
- JavaScript Promises by David M. Lee (Nodevember 2014)
- David M. Lee的JavaScript承诺(Nodevember 2014)
UPDATE (2016)
There is a new syntax in ECMA-262, 6th Edition, Section 14.2 called arrow functions that may be used to further simplify the examples above.
在第6版的ECMA-262中有一种新的语法,叫做箭头函数,可以用来进一步简化上面的示例。
Using the jQuery API, instead of:
使用jQuery API,而不是:
promise.success(function (data) {
alert(data);
});
you can write:
你可以写:
promise.success(data => alert(data));
or using the Promises/A+ API:
或使用promise /A+ API:
promise.then(data => alert(data));
Remember to always use rejection handlers either with:
记住一定要使用拒绝处理程序:
promise.then(data => alert(data), error => alert(error));
or with:
或:
promise.then(data => alert(data)).catch(error => alert(error));
See this answer to see why you should always use rejection handlers with promises:
请查看此答案,以了解为什么您应该始终使用带有承诺的拒绝处理程序:
- Should I refrain from handling Promise rejection asynchronously?
- 我应该避免异步地处理承诺拒绝吗?
Of course in this example you could use just promise.then(alert)
because you're just calling alert
with the same arguments as your callback, but the arrow syntax is more general and lets you write things like:
当然,在这个例子中,你可以使用promisethen (alert)因为你调用alert的参数和回调的参数相同,但是箭头语法更一般,你可以这样写:
promise.then(data => alert("x is " + data.x));
Not every browser supports this syntax yet, but there are certain cases when you're sure what browser your code will run on - e.g. when writing a Chrome extension, a Firefox Add-on, or a desktop application using Electron, NW.js or AppJS (see this answer for details).
并不是所有的浏览器都支持这种语法,但是在某些情况下,当你确定你的代码将运行在哪个浏览器上时——例如,当你编写Chrome扩展、Firefox扩展或使用电子的桌面应用程序时。js或AppJS(详细信息请参见此答案)。
For the support of arrow functions, see:
箭头函数的支持,见:
- http://caniuse.com/#feat=arrow-functions
- = arrow-functions http://caniuse.com/壮举
- http://kangax.github.io/compat-table/es6/#test-arrow_functions
- http://kangax.github.io/compat-table/es6/ test-arrow_functions
UPDATE (2017)
There is an even newer syntax right now called async functions with a new await
keyword that instead of this code:
现在有一种更新的语法叫做异步函数,它有一个新的wait关键字而不是这个代码:
functionReturningPromise()
.then(data => console.log('Data:', data))
.catch(error => console.log('Error:', error));
lets you write:
让你写:
try {
let data = await functionReturningPromise();
console.log('Data:', data);
} catch (error) {
console.log('Error:', error);
}
You can only use it inside of a function created with the async
keyword. For more info, see:
您只能在用async关键字创建的函数中使用它。更多信息,请参见:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
For support in browsers, see:
对于浏览器中的支持,请参见:
- http://caniuse.com/async-functions
- http://caniuse.com/async-functions
For support in Node, see:
对于节点内的支持,请参见:
- http://node.green/#ES2017-features-async-functions
- http://node.green/ ES2017-features-async-functions
In places where you don't have native support for async
and await
you can use Babel:
在没有异步本地支持的地方,您可以使用Babel:
- https://babeljs.io/docs/plugins/transform-async-to-generator/
- https://babeljs.io/docs/plugins/transform-async-to-generator/
or with a slightly different syntax a generator based approach like in co
or Bluebird coroutines:
或者使用稍微不同的语法,基于生成器的方法,比如co或Bluebird coroutines:
- https://www.npmjs.com/package/co
- https://www.npmjs.com/package/co
- http://bluebirdjs.com/docs/api/promise.coroutine.html
- http://bluebirdjs.com/docs/api/promise.coroutine.html
More info
Some other questions about promises for more details:
关于承诺更多细节的其他问题:
- promise call separate from promise-resolution
- 承诺召唤与承诺决定分开
- Q Promise delay
- 问承诺延迟
- Return Promise result instead of Promise
- 回报承诺,而不是承诺
- Exporting module from promise result
- 从承诺结果导出模块
- What is wrong with promise resolving?
- 承诺解决有什么问题?
- Return value in function from a promise block
- 从承诺块返回函数值
- How can i return status inside the promise?
- 如何在承诺中返回状态?
- Should I refrain from handling Promise rejection asynchronously?
- 我应该避免异步地处理承诺拒绝吗?
- Is the deferred/promise concept in JavaScript a new one or is it a traditional part of functional programming?
- JavaScript中的延迟/承诺概念是新概念还是函数式编程的传统部分?
- How can I chain these functions together with promises?
- 如何将这些函数和承诺联系起来?
- Promise.all in JavaScript: How to get resolve value for all promises?
- 的承诺。JavaScript:如何获得所有承诺的解析值?
- Why Promise.all is undefined
- 为什么承诺。都是未定义的
- function will return null from javascript post/get
- 函数将从javascript post/get返回null
- Use cancel() inside a then-chain created by promisifyAll
- 在promisifyAll创建的then-chain中使用cancel()
- Why is it possible to pass in a non-function parameter to Promise.then() without causing an error?
- 为什么可以将非函数参数传递给promisethen()而不会导致错误?
- Implement promises pattern
- 实现承诺模式
- Promises and performance
- 承诺和性能
- Trouble scraping two URLs with promises
- 用承诺抓取两个url有困难
- http.request not returning data even after specifying return on the 'end' event
- http。即使在指定“结束”事件的返回之后,也不要返回数据
- async.each not iterating when using promises
- 异步。当使用承诺时,每个都不重复
- jQuery jqXHR - cancel chained calls, trigger error chain
- jQuery jqXHR -取消链式调用,触发错误链。
- Correct way of handling promisses and server response
- 正确处理承诺和服务器响应的方式
- Return a value from a function call before completing all operations within the function itself?
- 在完成函数本身中的所有操作之前,从函数调用返回一个值?
- Resolving a setTimeout inside API endpoint
- 解决API端点内部的setTimeout
- Async wait for a function
- 异步等待一个函数
- JavaScript function that returns AJAX call data
- 返回AJAX调用数据的JavaScript函数
- try/catch blocks with async/await
- 与异步/等待try / catch块
- jQuery Deferred not calling the resolve/done callbacks in order
- jQuery没有按顺序调用解析/完成的回调
- Returning data from ajax results in strange object
- 从ajax返回数据会产生奇怪的对象
- javascript - Why is there a spec for sync and async modules?
- 为什么有一个用于同步和异步模块的规范?
#3
146
you can add async option to false and return outside the ajax call.
您可以将async选项添加到false,并在ajax调用之外返回。
function testAjax() {
var result="";
$.ajax({
url:"getvalue.php",
async: false,
success:function(data) {
result = data;
}
});
return result;
}
#4
0
Idk if you guys solved it but I recommend another way to do it, and it works :)
Idk,如果你们解出来了但我推荐另一种方法,它是有效的
ServiceUtil = ig.Class.extend({
base_url : 'someurl',
sendRequest: function(request)
{
var url = this.base_url + request;
var requestVar = new XMLHttpRequest();
dataGet = false;
$.ajax({
url: url,
async: false,
type: "get",
success: function(data){
ServiceUtil.objDataReturned = data;
}
});
return ServiceUtil.objDataReturned;
}
})
So the main idea here is that, by adding async: false, then you make everything waits until the data is retrieved. Then you assign it to a static variable of the class, and everything magically works :)
这里的主要思想是,通过添加async: false,您可以让所有的东西都等待,直到数据被检索。然后将其赋值给类的静态变量,然后一切魔术般地工作:)
#5
-10
See jquery docs example: http://api.jquery.com/jQuery.ajax/ (about 2/3 the page)
参见jquery文档示例:http://api.jquery.com/jQuery.ajax/(大约2/3页)
You may be looking for following code:
您可能正在寻找以下代码:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Same page...lower down.
同一页面…低下来。