class Y {
constructor() {
this.promises = new Array();
}
push(promise) {
this.promises.push(_ => promise)
}
}
async function runPromisesInSequence(promises) {
for (let promise of promises) {
console.log(await promise());
}
}
const pr1 = new Promise(res => setTimeout(() => res('r1'), 1000));
const pr2 = new Promise(res => setTimeout(() => res('r2'), 5000));
const pr3 = new Promise(res => setTimeout(() => res('r3'), 0));
let y = new Y();
y.push(pr1);
y.push(pr2);
y.push(pr3);
runPromisesInSequence(x.promises)
async function delayedPromise(cb) {
const delay = () => new Promise(resolve => setTimeout(resolve, 3000));
const result = await Promise.all([cb(), delay()]);
return result[0];
}
async function runPromisesInSequence(promises) {
for (let promise of promises) {
console.log(await delayedPromise(promise), new Date());
}
}
const pr1 = () => new Promise(res => setTimeout(() => res('r1'), 1000));
const pr2 = () => new Promise(res => setTimeout(() => res('r2'), 5000));
const pr3 = () => new Promise(res => setTimeout(() => res('r3'), 0));
const y = [pr1, pr2, pr3];
runPromisesInSequence(y);
const pr1 = new Promise(res => setTimeout(() => res('r1'), 1000));
const delay = _ => new Promise(rs => setTimeout(rs, 3e3));
async function notSoFast(promise) {
result = await Promise.all([ promise, delay()]);
return result[0];
}
async function runPromisesInSequence(promises) {
for (let i=0; i<promises.length; i++) {
if(i === 0) {
console.timeEnd( await promises[0]);
} else {
console.timeEnd( await notSoFast(promises[i]));
}
}
}
function makePr(label, dur) {
return new Promise(rs => {
console.log('%s started', label);
console.time(label); // начало отсчёта
setTimeout(_ => {
console.log('%s timer completed', label);
rs(label);
}, dur);
});
}
runPromisesInSequence([
makePr('r1', 1000),
makePr('r2', 5000),
makePr('r3', 0000),
]);
/* Выводит:
r1 started
r2 started
r3 started
r3 timer completed
r1 timer completed
r1: 1005ms
r2 timer completed
r2: 5007ms
r3: 8009ms
*/