调用者没有从ajax的异步方法获得正确的值

问题描述 投票:0回答:2

我试图围绕一个承诺包装我的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();

我在resultgetDetails()得到了正确的价值。 test()中的result是一个promise对象而不是期望值。

我应该如何使用Promises以异步方式从getDetails获取所需的值?

javascript ajax promise async-await
2个回答
3
投票

那是因为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}`));
}

更好的是:使用新的qazxsw poi API

既然你正在使用ES6,你可能还是要考虑fetch()

using the fetch() API

1
投票

当你将一个函数声明为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 Documentationresolve,从而允许您将返回值视为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(); 可以为你做这份工作。

© www.soinside.com 2019 - 2024. All rights reserved.