Javascript 像async一样逐个运行函数,但不使用async

Javascript 像async一样逐个运行函数,但不使用async,javascript,jquery,function,async-await,.post,Javascript,Jquery,Function,Async Await,.post,其中一个将连接到php页面并获取一些数据,而我的另一个函数将使用第一个函数收集的新数据更改一些html代码 例如,这是我的代码: var $data; firstFunction(){ $.post("index.php",{},function(data){$data=data;}); } secondFunction(){ $("body").empty().append($data); } firstFunction(); secon

其中一个将连接到php页面并获取一些数据,而我的另一个函数将使用第一个函数收集的新数据更改一些html代码

例如,这是我的代码:

var $data;
firstFunction(){
    $.post("index.php",{},function(data){$data=data;});
}
secondFunction(){
    $("body").empty().append($data);
}
firstFunction();
secondFunction();
因此,在上面的代码中,如果我们运行此函数,它将开始收集数据,但在完成收集数据之前,它将运行第二个函数,这是不正确的,并且它必须在第一个函数完成以下操作后运行第二个函数:

$.when(firstFunction()).done(function(){secondFunction();});
var $data;
firstFunction(){
    $.post("index.php",{},function(data){$data=data;secondFunction();});
}
secondFunction(){
    $("body").empty().append($data);
}
firstFunction();
但它不太管用,我知道有一种叫做async的东西,但我想知道是否还有其他方法可以在不改变函数的情况下做到这一点,如果可能的话,请给我一个async的例子

而且我不想改变函数我的意思是我知道我可以这样做:

$.when(firstFunction()).done(function(){secondFunction();});
var $data;
firstFunction(){
    $.post("index.php",{},function(data){$data=data;secondFunction();});
}
secondFunction(){
    $("body").empty().append($data);
}
firstFunction();
正如您在新代码中所看到的,第二个函数将在第一个权限完成它的工作后运行,但我不能,我不想这样做,我希望类似于异步的东西,但如果可能的话,以其他方式,因为我有许多函数,它将需要很长时间来更改主题


非常感谢。

尝试在脚本标记中使用async属性:

<script src="demo_async.js" async></script>


<> >资源:

你可能想考虑使用一个像Axios这样的基于承诺的库,你可以用这个方法同时使用AsiNc/Acess和承诺链接。您可以使用带有CDN的脚本标记或通过NPM/Thread将其引入应用程序

以下是异步等待的示例:

async function getData(){

 async function getPosts(){
  try {
   const response = await 
   axios.get('https://jsonplaceholder.typicode.com/posts/1');
    return response
   } catch (error) {
    console.error(error);
   }
 }

 var Posts = await getPosts();
 document.getElementById('posts').textContent = JSON.stringify(Posts.data);

 async function getComments(){
  try {
   const response = await 
   axios.get('https://jsonplaceholder.typicode.com/comments/1');
    return response
   } catch (error) {
   console.error(error);
   } 
 }


  var Comments = await getComments();
  document.getElementById('comments').textContent = 
  JSON.stringify(Comments.data);
}


据我所知,这是唯一可行的方法