【问题标题】:run functions one by one after each other like async but without async像异步一样一个接一个地运行函数,但没有异步
【发布时间】:2021-04-30 22:43:40
【问题描述】:

其中一个将连接到 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();

正如您在新代码中看到的那样,第二个函数将在第一个权限完成后运行,但我不能也不想这样做功能多,更换主题需要很长时间。

非常感谢。

【问题讨论】:

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

标签: javascript jquery function async-await .post


【解决方案1】:

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

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

来源:https://www.w3schools.com/tags/att_script_async.asp

【讨论】:

    【解决方案2】:

    您可能需要考虑使用像 Axios 这样基于 Promise 的库,您可以将 async/await 与此方法以及 Promise 链接一起使用。您可以使用带有 CDN 的脚本标签或通过 NPM/Yarn 将其引入您的应用程序。

    https://github.com/axios/axios

    这是一个异步等待的例子:

    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);
    

    }

    https://jsfiddle.net/Lm2c6r40/

    【讨论】:

      猜你喜欢
      • 2019-05-22
      • 2022-11-22
      • 2020-09-17
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 2020-11-15
      • 2021-01-15
      • 1970-01-01
      相关资源
      最近更新 更多