// Gets called if a parameter is missing and the expression // specifying the default value is evaluated. const throwIfMissing = () => { thrownewError('Missing parameter'); } const func = (requiredParam = throwIfMissing()) => { // some implementation }
// Wrap `setTimeout` in a promise such that if // the timeout completes, the promise is rejected const timeout = (delay = 30000) => { returnnewPromise((resolve, reject) => { let rejectWithError = () => { reject(newError('Timed out!')); };
setTimeout(rejectWithError, delay); }); }
// Return a promise that will be fulfilled if // the fetch is fulfilled before the timeout // is rejected. const fetchWithTimeout = (url, delay = 3000) => { // construct an array to pass to `Promise.race` returnPromise.race([ fetch(url), timeout(delay) ]); }
// Make an XHR request for the URL that has to // return a response *before* the 1 s timeout // happens fetchWithTimeout('/json/data.json', 1000) .then(response => { // successful response before the 1 s timeout console.log('successful response', response) }) .catch((e) => { // Either the timeout occurred or some other error. // Would need to check the method or use a custom // `Error` subclass in `timeout` console.error('request error', e); });
classNote{ constructor() { if (new.target === Note) { thrownewError('Note cannot be directly constructed.') } } } classColorNoteextendsNote{
} let note = new Note(); // error! let colorNote = new ColorNote(); // ok
12. 定义懒长度函数
知识点:generators
1 2 3 4 5 6 7 8 9 10 11
// Return a new generator that will iterate from `start` for // `count` number of times function* range(start, count) { for (let delta = 0; delta < count; delta++) { yield start + delta; } }
for (let teenageYear of range(13, 7)) { console.log(`Teenage angst @ ${teenageYear}!`); }