javascript - 在 javascript 中进行同步 api 调用

标签 javascript jquery ajax

我在 javascript 中有一个调用 GET api 的方法

var PC;
    function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PC= response;
        }
    });
}

我正在名为 PC 的变量中设置响应,并在另一种方法中调用它

function PerformTask()
{
GetDetails();
console.log(PC);
}

在 GetDetails 方法中 console.log(response);有效,但在 PerformTask() 中 console.log(PC) 未定义

据我了解,这是一个异步调用,PC 尚未设置

我怎样才能让它与下一个语句同步,??因为我需要 PC 的值来执行下一组语句

我还尝试了 fetch api 调用

fetch(Myurl)
        .then(resp => resp.json())
          .then(resp=> setting variable here) ;

但它不起作用(工作但以异步方式)

更新1

return new Promise(function (resolve, reject) {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);;
            resolve(response);
        },
        error: function (err) {
            reject(err);
        }
    });
});

并在 Performtask() 中

GetPropertyDetails()
    .then(function (data) {
        PC= data;
    });
console.log(PC);

但 PC 仍然未定义

最佳答案

成功后,您可以调用另一个需要响应的方法。由于调用是异步的,因此该函数将不会获得响应。

var PC;
function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PC= response;
            // Your next function 
            PerformTask(PC);
        }
    });
}

function PerformTask(pc)
{
    GetDetails();
    console.log(pc);
}

还有另一种方法可以做到这一点,但我认为这是不好的方法

$.ajax({
            type: "GET",
            url: Myurl,
            async:false,
            success: function (response) {
                //console.log(response);
                PC= response;
                // Your next function 
                PerformTask(PC);
            }
        });

使用promise =>您可以使用asyncawait

function asyncCall() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(5)
    }, 2000)
  });
}

(async function() {
  const result = await asyncCall();
  if (result) console.log(result)
})()

希望这对您有帮助。

关于javascript - 在 javascript 中进行同步 api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56334662/

相关文章:

javascript - 如何根据 ajax 错误响应禁用元素

javascript - Node.js 在执行函数之前需要等待 for 循环完成

javascript - 为什么会有 NaN?

javascript - 如何使用 jQuery 使用多个数据属性和多个逻辑条件选择 li

javascript - 从 Ajax 函数的代码隐藏中调用 C# 函数

jquery - IE7-Ajax 成功数据已过时

javascript - DOM 帮助(显示水果的无序列表并给每个水果一个类)

JavaScript - 删除样式

asp.net - 使用 .Net 验证器在无效时将类添加到文本框

javascript - 如何将 HTML 字符串作为 DOM 元素从 Flask 应用程序传递到 HTML 模板,然后 appendChild