我在 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
=>您可以使用async
和await
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/