问题 Promise.all()
Issue Promise.all()
我想声明一个空承诺数组
然后手动解决它们,但它不起作用?
const tab = [1]
let promises = tab.map(e => new Promise(() => { }))
setTimeout(() => {
promises[0] = Promise.resolve()
}, 3000);
Promise.all(promises)
.then(e => console.log("finished"))
我不想这样做:
const tab = [1]
let promises = tab.map(e => new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 3000);
}))
Promise.all(promises)
.then(e => console.log("finished"))
这是你能得到的最接近的:
const tab = [1]
let resolves = []
let promises = tab.map(e => new Promise((resolve) => {
resolves.push(resolve)
}))
setTimeout(() => {
resolves[0]()
}, 3000);
Promise.all(promises).then(e => console.log("finished"))
这是一种使用可重用 deferred
函数的技术,可让您从外部控制承诺。我们扩展了 resolve
和 reject
功能,以便更好地控制调用者。这是一种有点非常规的模式,但以这种方式利用 promise 有很多优势。有关详细示例,请参阅 -
function deferred () {
let resolve, reject, promise = new Promise((res, rej) => {
resolve = res; reject = rej
})
return { promise, resolve, reject }
}
const tasks = [ deferred(), deferred(), deferred() ] // 3 "deferrred" objects
Promise.all(tasks.map(t => t.promise)).then(console.log, console.error)
setTimeout(_ => tasks[0].resolve("one"), 1000)
setTimeout(_ => tasks[1].resolve("two"), 2000)
setTimeout(_ => tasks[2].resolve("three"), 3000)
我想声明一个空承诺数组
然后手动解决它们,但它不起作用?
const tab = [1]
let promises = tab.map(e => new Promise(() => { }))
setTimeout(() => {
promises[0] = Promise.resolve()
}, 3000);
Promise.all(promises)
.then(e => console.log("finished"))
我不想这样做:
const tab = [1]
let promises = tab.map(e => new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 3000);
}))
Promise.all(promises)
.then(e => console.log("finished"))
这是你能得到的最接近的:
const tab = [1]
let resolves = []
let promises = tab.map(e => new Promise((resolve) => {
resolves.push(resolve)
}))
setTimeout(() => {
resolves[0]()
}, 3000);
Promise.all(promises).then(e => console.log("finished"))
这是一种使用可重用 deferred
函数的技术,可让您从外部控制承诺。我们扩展了 resolve
和 reject
功能,以便更好地控制调用者。这是一种有点非常规的模式,但以这种方式利用 promise 有很多优势。有关详细示例,请参阅
function deferred () {
let resolve, reject, promise = new Promise((res, rej) => {
resolve = res; reject = rej
})
return { promise, resolve, reject }
}
const tasks = [ deferred(), deferred(), deferred() ] // 3 "deferrred" objects
Promise.all(tasks.map(t => t.promise)).then(console.log, console.error)
setTimeout(_ => tasks[0].resolve("one"), 1000)
setTimeout(_ => tasks[1].resolve("two"), 2000)
setTimeout(_ => tasks[2].resolve("three"), 3000)