13.1.1 Timer
let updateIntervalId=setInterval(checkForUpdates,60000);
function stopCheckingForUpdates(){clearInterval(updateIntervalId);
}
事件
let okay=document.querySelector('#confirmUpdateDialog button.okay');
okay.addEventListener('click',applyUpdate);
applyUpdate是一个假设的callback函数。当用户点击了指定区域后会执行这个函数。
13.1.3 网络事件
function getCurrentVersionNumber(versionCallback){let request=new XMLHttpRequest();request.open("GET","http://www.example.com/api/version");request.send();request.onload=function(){if(request.status==200){//good statuslet currentVersion=parseFloat(request.responseText);versionCallback(null,currentversion);
}else{versionCallback(response.statusText,null);}
};request.onerror=request.ontimeout=function(e){versionCallback(e.type,null);};
}
13.2Promises
Promise是一个代表异步计算结果的对象
Promise代表了单个异步计算的未来结果,不能用于重复异步计算。
getJSON(url).then(jsonData=>{/*This is a callback function that will be asynchronously invoked with the parsed JSON value when it becomes available*/
});
getJSON()开始于一个异步HTTP请求,请求Url。当request待处理时,返回一个Promise对象。Promise对象定义了一个then()实例方法。我们不直接把callback函数交给getJSON(),而是交给then()方法。当HTTP请求到达时,HTTP body会被转化为JSON,转化结果会传递给then()中,我们定义的函数。
你可以把then()方法想象为addEventListener()方法,用于注册句柄。
Promise对象代表了一次计算,then()方法注册的函数应该只被调用一次。
例
function displayUserProfile(profile){}//用于获得用户信息的函数getJSON("/api/user/profile").then(displayUserProfile);//注册then()
用Promise处理错误。
办法是传递第二个函数给then()方法。
getJSON("/api/user/profile").then(displayUserProfile,handleProfileError);
一种更加地道的解决方法是
getJSON("/api/user/profile").then(displayUserProfile).catch(handleProfileError);