// Polyfill
function at(n) {
// ToInteger() abstract op
n = Math.trunc(n) || 0;
// Allow negative indexing from the end
if(n < 0) n += this.length;
// OOB access is guaranteed to return undefined
if(n < 0 || n >= this.length) return undefined;
// Otherwise, this is just normal property access
return this[n];
}
async function doJob() {
const rawResource = await fetch('//domain/resource-a')
.catch(err => {
throw new Error('Download raw resource failed', { cause: err });
});
const jobResult = doComputationalHeavyJob(rawResource);
await fetch('//domain/upload', { method: 'POST', body: jobResult })
.catch(err => {
throw new Error('Upload job result failed', { cause: err });
});
}
try {
await doJob();
} catch (e) {
console.log(e);
console.log('Caused by', e.cause);
}
// Error: Upload job result failed
// Caused by TypeError: Failed to fetch
四、管道运算符 # w; X V& c, O. z9 l 这个语法的Star特别多,有5k多个,侧面也能说明是个受欢迎的语法,但是距离发布应该还有好久,毕竟这个提案三四年前就有了,目前还只到阶段 1。这个语法其实在其他函数式编程语言上很常见,主要是为了函数调用方便:' r- [: z' h7 f! I+ F
let result = exclaim(capitalize(doubleSay("hello")));
result //=> "Hello, hello!"
let result = "hello"
|> doubleSay
|> capitalize
|> exclaim;
result //=> "Hello, hello!"
这只是对于单个参数的用法,其它的用法有兴趣的读者可以自行阅读提案,其中涉及到了特别多的内容,这大概也是导致推进阶段慢的原因吧。 . w- Y W% L7 I- _' M6 U五、新的数据结构:Records & Tuples 6 k) _$ H, T, z+ R0 f 这个数据结构笔者觉得发布以后会特别有用,总共新增了两种数据结构,可以通过#来声明:& N% L9 x' X {% |! l1 y' i
#{ x: 1, y: 2 } ! B' E) I6 ^6 u% u2 T& X! x4 f#[1, 2, 3, 4]
& D/ T& w* S0 f1 R9 v$ \) t 这种数据结构是不可变的,类似 React 中为了做性能优化会引入的 immer 或者 immutable.js,其中的值只接受基本类型或者同是不可变的数据类型。 7 H- j7 {! N9 J. r+ y% ]