首页 > 解决方案 > 在javascript中进行同步api调用

问题描述

我在 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仍然是未定义的

标签: javascriptjqueryajax

解决方案


从成功开始,您可以调用另一个需要响应的方法。由于调用ASYNC如此,函数将不会得到响应。

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=> 你可以使用async&await

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

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

希望这对您有所帮助。


推荐阅读