javascript - 在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仍然是未定义的
解决方案
从成功开始,您可以调用另一个需要响应的方法。由于调用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)
})()
希望这对您有所帮助。
推荐阅读
- python-3.x - 努力在 PyCharm 中渲染可视化 - 有谁能提供帮助吗?
- javascript - 在奇怪且罕见的基于 es3 的环境中获取对全局对象的引用
- direct3d - 检索 D3D12 视频解码状态
- php - 我有一个 PHP 脚本可以使用此代码发送电子邮件-
- python - TclError:CentOS 中没有显示名称和 $DISPLAY 环境变量
- c# - 如何隐藏 DataGridVew 行
- php - 将 xampp 指向公共文件夹/仅用于一个项目的不同文件夹
- javascript - 函数不会执行里面的查询
- perl - Perl - 变量的值不在条件下工作
- android - 从 Android Activity 导航到 Fragment