官术网_书友最值得收藏!

The callback pattern on the web

The way to go about it is to attach functions to future events. When the event occurs, our attached function gets executed. An example of this is XMLHttpRequest, which looks like this:

const xhr = new XMLHttpRequest();
xhr.open('GET','/path', true);
xhr.onload = () => {
// run me when the request is finished
}

xhr.send(null);

What we can see here is that all lines are executed synchronously except for xhr.onload. Attaching the function to onload happens synchronously, but running the function that onload is pointing to doesn't happen until the request finishes. We can also define other events, such as onreadystatechange , and attach a function to that as well:

xhr.onreadystatechange = () => {}

As the web is single-threaded, this is how we deal with asynchronous code. The onreadystatechange object and its callback are registered with the operating system. Once the asynchronous part has been completed the operating system is woken up by an event being dispatched. Thereafter, the callback is invoked.  

主站蜘蛛池模板: 永福县| 新安县| 巴南区| 泸西县| 馆陶县| 榆树市| 吐鲁番市| 永济市| 盐源县| 镇平县| 莲花县| 定州市| 临湘市| 赣榆县| 武清区| 忻城县| 当涂县| 安阳市| 新龙县| 太康县| 澳门| 多伦县| 廊坊市| 潮州市| 四平市| 江陵县| 高要市| 甘孜| 赣榆县| 淮阳县| 古交市| 株洲县| 内江市| 巫山县| 息烽县| 赤城县| 宜阳县| 安仁县| 咸阳市| 荔浦县| 区。|