js高级程序设计阅读第十一章-异步

58 阅读1分钟

reduce使用

function addTwo(x) {return x + 2;} 
function addThree(x) {return x + 3;} 
function addFive(x) {return x + 5;} 
function compose(...fns) { 
return (x) => fns.reduce((promise, fn) => promise.then(fn), Promise.resolve(x)) 
} 
let addTen = compose(addTwo, addThree, addFive);
addTen(8).then(console.log); // 18

期约进度通知

没看懂
class TrackablePromise extends Promise {
constructor(executor) {
    const notifyHandlers = [];
    super((resolve, reject) => {
        return executor(resolve, reject, (status) => {
            notifyHandlers.map((handler) => handler(status));
        });
    });
    this.notifyHandlers = notifyHandlers;
}
notify(notifyHandler) {
    this.notifyHandlers.push(notifyHandler);
    return this;
    }
}
let p = new TrackablePromise((resolve, reject, notify) => {
    function countdown(x) {
        if (x > 0) {
            notify(`${20 * x}% remaining`);
            setTimeout(() => countdown(x - 1), 1000);
        } else {
            resolve();
        }
    }
    countdown(5);
}); 

await

JavaScript 运行时在碰到 await 关键字时,会记录在哪里暂停执行。等到 await 右边的值可用了,JavaScript 运行时会向消息队列中推送一个任务,这个任务会恢复异步函数的执行。