Interview question: javascript implement Promise.all

Witch Elaina
Oct 11, 2021

promiseAll.js

var promiseAll = (ps) => {
return new Promise((resolve) => {
var c = ps.length
for (var p of ps) {
p.then(() => {
c--
if (c == 0) {
resolve()
}
})
}
})
}
describe("promiseAll", () => {
it("1", () => {
var ps = []
ps.push(new Promise((resolve) => {
setTimeout(() => {
console.log("p1")
resolve()
}, 100)
}))
ps.push(new Promise((resolve) => {
setTimeout(() => {
console.log("p2")
resolve()
}, 200)
}))
return promiseAll(ps).then(() => {
console.log("finish all")
})
})
})

If you like my article, donate me a coffee and let me continue

Donate

Donate backup

--

--