(function test(queue) { const fn = queue.shift() fn(s => { runCallback(s) if (queue.length) test(queue) }) })([one, two, three]) пример с рекурсией :) |
Ну если воспользоваться идеями Aetae и Alexandroppolus и попытаться объединить их, то получается такой вариант
function one(callback) { setTimeout( function() { callback("First"); }, Math.random() * 1000); } function two(callback) { setTimeout( function() { callback("Second"); }, Math.random() * 500); } function three(callback) { setTimeout( function() { callback("Third"); }, Math.random() * 100); } function runCallback(s) { console.log(s); } async function stream(log, ...args) { const ap = args.map (func => new Promise(func)) for (let i = 0; i < args.length; i++) { log(await ap[i]) } } stream(runCallback, one, two, three) |
Тогда так на колбеках :)
function one(callback) { setTimeout( function() { callback("First"); }, Math.random() * 1000); } function two(callback) { setTimeout( function() { callback("Second"); }, Math.random() * 500); } function three(callback) { setTimeout( function() { callback("Third"); }, Math.random() * 100); } function runCallback(s) { console.log(s); } const stream = (log, ...queue) => queue.shift()(s => (log(s), queue.length && stream(log, ...queue))) stream(runCallback, one, two, three) |
Цитата:
|
Цитата:
Цитата:
|
voraa, во, вот это мило.)
Ток можно вот так вот модняво записать, чтоб ваще: async function stream(log, ...args) { for await(let result of args.map(func => new Promise(func))) { log(result) } } Жаль в js нельзя как в жабе сделать так: args.map(Promise::new), тогдаб вообще идеально было.) |
Цитата:
|
тот же вариант без асинк/авайт:
function stream(log, ...args) { args.reduce((acc, func) => { const prom = new Promise(func); return acc.then(() => prom).then(log); }, Promise.resolve()); } |
Alexandroppolus, да обычный расколабас. Те же классы которые через class не могут работать без new по спеке.
Всегда можно сделать хрень типа: window.Promise = new Proxy(Promise, { apply (target, _, args) { return new target(...args); } });но как-то оно... |
Пошла битва за буковки :haha:
const stream = (log, ...args) => args.reduce((a, f) => a.then(_ => new Promise(f)).then(log), Promise.resolve()); const stream = (log, ...args) => args.shift()(s => (log(s), args.length && stream(log, ...args))) |
Часовой пояс GMT +3, время: 16:15. |