是否可以在没有return关键字的情况下解析异步功能
我开始使用ES7功能async/await
,它提供了处理异步任务的最佳方法,并使您的代码更清晰易读.
I started to use ES7 feature async/await
, which gives the best approach to deal with asynchronous tasks, and makes your code cleaner and readable.
但是,它不能让您访问由异步函数创建的Promise,因此,如果您在异步函数中执行了一些异步请求,则应该对它进行Promisise,然后等待它,然后返回结果.我的意思是:
However it doesn't give you an access to Promise, created by async function, so if you do some async request in your async function you should promisify it, then await it and then return the result. I mean this:
async function doStuff() {
//stuff...
var value = await new Promise(function(resolve) {
$.get('http://some/url/...', function(result) {
// stuff...
resolve(result);
});
});
return value;
}
如果您可以找到一个指向由函数创建的Promise的指针,那么您的代码可能如下所示:
What if you could find a pointer to the Promise created by function so your code could look like:
async function doStuff() {
//stuff...
var p = arguments.callee.promise;
$.get('http://some/url/...', function(result) {
// stuff...
p.resolve(result);
});
}
甚至:
async function doStuff() {
//stuff...
$.get('http://some/url/...', function(result) {
// stuff...
async.resolve(result);
});
}
通过这种方式,您无需直接访问Promises API,这使您的代码完全专注于任务,没有任何其他要求.
This way you don't need to directly access Promises API what makes your code totally focused on task without any besides.
是否可以在没有return关键字的情况下解析异步功能
Is it possible to resolve async function without return keyword
否.
没有办法引用对创建async function
的调用的promise,但是实际上也不需要访问它(而且顺便说一句,您不能.resolve()
一个promise,实际上需要访问诺言的解决功能.
There is no way to get a reference to the promise that the call to the async function
created, but there really is no need to access that either (and btw, you cannot .resolve()
a promise, you'd actually need to get access to the promise's resolving functions).
async
/await
的全部要点是与promise和其他thenable玩得很好.这个想法是,每个异步函数都返回一个promise,并且您不必承诺任何内容(但是,如果确实需要,则可以单独做)-实际上,$.get
执行返回(jQuery)Promise.所以只需写
The whole point of async
/await
is to play nice with promises and other thenables. The idea is that every asynchronous function returns a promise, and that you don't have to promisify anything (but if you really have to, do it separately) - and in fact, $.get
does return a (jQuery) promise. So simply write
async function doStuff() {
//stuff...
var result = await $.get('http://some/url/...');
// stuff...
return someValue;
}
如果您确实具有回调函数,请使用简单的
If you really have a callback-taking function, use a simple
async function doStuff() {
// stuff…
return new Promise(function(resolve, reject) {
$.get({
url: 'http://some/url/...',
success: resolve,
error: reject
// don't do other "stuff" in here
});
});
}