js等待异步方法结束后回调
Welcome to the crash course on Async JS.
欢迎使用Async JS速成班。
Callback, Promises, and Async-await are a way to deal with asynchronous data. Asynchronous programming in JavaScript is a way in which the program doesn’t wait until the execution of something is going on.
回调,承诺和异步等待是一种处理异步数据的方法。 JavaScript中的异步编程是一种这样的方法,即程序不等到正在执行某些事情时才进行操作。
This comes in handy when we do an API call to fetch some data, which takes some time (maybe 2–3 sec). But we don’t want our program to stop executing the next statements and this is known as Async JS.
当我们执行API调用以获取一些数据时,这很方便,这需要一些时间(可能需要2到3秒)。 但是我们不希望我们的程序停止执行下一条语句,这就是Async JS。
So, let’s start with a jsbin and open the JavaScript and the Output. Here, we had created an Array of objects posts, which contains two Objects.
因此,让我们从jsbin开始,然后打开JavaScript和Output。 在这里,我们创建了一个对象数组,其中包含两个对象。
Now, we have a function getPosts() and inside it, we have setTimeout() to mimic the call to an API server, which runs with a delay of 1000 milliseconds. After that, we are just looping through the posts and adding li and p containing title and summary to the output.
现在,我们有了一个函数getPosts(),并且在其中有setTimeout()来模拟对API服务器的调用,该服务器以1000毫秒的延迟运行。 之后,我们只是循环浏览这些帖子,并将包含标题和摘要的li和p添加到输出中。
Once the forEach is complete, we are adding it to the body.
一旦forEach完成,我们将其添加到主体中。
After that, we have createPost(), which just pushes a new post to the posts array. But it runs after 2000 milliseconds.
之后,我们有了createPost() ,它只是将新帖子推送到posts数组。 但是它会在2000毫秒后运行。
![Image for post](https://img-blog.csdnimg.cn/img_convert/724959a548876bad7948965c932e5e68.png)
We ca