Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is a callback function in js

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you what is a callback function in js, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

What is a callback function? What are the disadvantages of callback function

A callback function is an executable code snippet that is passed as an argument to other code to facilitate calling this code when needed.

In JavaScript, a function is also a kind of object, and the same object can be passed to the function as an argument, so the function can also be passed to another function as an argument, and the function as a parameter is the callback function.

Const btnAdd = document.getElementById ('btnAdd'); btnAdd.addEventListener (' click', function clickCallback (e) {/ / do something useless})

In this case, we wait for the click event in the element where id is btnAdd, and if it is clicked, the clickCallback function is executed. The callback function adds some functionality to certain data or events.

The callback function has a fatal weakness, which is that it is easy to write callback hell (Callback hell). Assume that multiple events have dependencies:

SetTimeout (() = > {console.log (1) setTimeout () = > {console.log (2) setTimeout () = > {console.log (3)}, 3000)}, 2000)}, 1000)

This is a typical callback hell. The above code does not seem to be easy to read and maintain, and once there are more events, it is even more messy, so Promise and async/await are proposed in es6 to solve the callback hell problem. Of course, the callback function has several other disadvantages, such as the inability to use try catch to catch errors and to return directly.

These are all the contents of the article "what is a callback function in js". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report