我试图围绕一个承诺包装我的ajax调用。因此,当ajax调用完成后,promise将得到解决。
在以下代码段中:
async function getDetails (data){
let promise = new Promise((resolve, reject) => {
$.ajax({
url: "/get-details",
type:"get",
contentType:"application/json",
data:{"text":data},
success: function(result){
resolve(result.response);
},
error: function(result){
reject(result.response);
}
});
});
let result = await promise;
console.log(`result: ${result}`);
return result;
}
function test() {
let result = getDetails("query-text");
console.log(`result in test : ${result}`);
}
test();
我在result
的getDetails()
得到了正确的价值。 test()中的result
是一个promise对象而不是期望值。
我应该如何使用Promises以异步方式从getDetails获取所需的值?
那是因为getDetails(...)
返回一个promise,而不是传递给resolve()
或reject()
回调的参数。因此,这样做应该工作:
async function test() {
let result = await getDetails("query-text");
console.log(`result in test : ${result}`);
}
或者,只需等待承诺解决,您就可以不使用async
方法:
function test() {
let p = getDetails("query-text");
p.then(result => console.log(`result in test : ${result}`));
}
既然你正在使用ES6,你可能还是要考虑fetch()
:
using the fetch()
API
当你将一个函数声明为async function getDetails (data){
let result = await fetch('/get-details').then(resp => resp.json());
console.log(`result: ${result.response}`);
return result.response;
}
async function test() {
let result = await getDetails("query-text");
console.log(`result in test : ${result}`);
}
test();
时,如果没有明确地这样做,它将隐式返回一个async
。这意味着你的Promise
函数将始终返回getDetails
。因此,您需要使用Promise
回调来从.then
获取结果,或者使用getDetails
从承诺中“解包”结果。
您可以在代码中更改的另一件事是您不需要在承诺中包装您的await
请求:
ajax
:
从jQuery 1.5开始,$ .ajax()返回的jqXHR对象实现了Promise接口,为它们提供了Promise的所有属性,方法和行为......
这意味着您的ajax请求将为您提供jQuery API Documentation和resolve
,从而允许您将返回值视为reject
,允许您将promise变量设置为直接等于您的ajax请求:
Promise
但是,正如@Terry在他的回答中指出的那样,如果你只是使用jQuery发送ajax请求,那么确实没有必要(除非你真的担心浏览器支持)。 async function getDetails(data) {
let promise = $.ajax({
url: "/get-details",
type: "get",
contentType: "application/json",
data: {
"text": data
}
});
let result = await promise;
console.log(`result: ${result}`);
return result; // returns a new promise with the return value as the resolve
}
async function test() {
let result = await getDetails("query-text"); // await to "unpack" the promise returned via your async function "getDetails"
console.log(`result in test : ${result}`);
}
test();
可以为你做这份工作。