在返回所有值之前,我如何等待所有承诺解决?
How can I wait for all promises to resolve before returning all their values?
我正在使用 bluebird 的 Promise.map
。在调度包含对象数组的事件之前,我试图等待所有承诺都解决。
readFiles() {
const fileArray = Array.from(this.fileSelectInput.files)
const promises = []
window.Promise.map(fileArray, (file, index) => {
return window.jsmediatags.read(file, {
onSuccess: tag => {
promises.push({
id: index + 1,
title: tag.tags.title || undefined,
artist: tag.tags.artist || undefined
})
promises.sort((a, b) => a.id - b.id)
console.log('I should be first')
}
})
}).then(() => {
console.log('I should be second')
this.dispatchEvent(new CustomEvent('tracks-selected', {
detail: promises
}))
}
}
我 运行 遇到 I should be second
在 I should be first
之前打印到控制台的问题。事件调度的 detail: promises
包含一个空数组。
您可能正在寻找
const fileArray = Array.from(this.fileSelectInput.files);
window.Promise.map(fileArray, file => {
return new Promise((resolve, reject) => {
window.jsmediatags.read(file, {
onSuccess: resolve,
// also pass reject as an error handler if jsmediatags supports that
});
});
}).then(tags => {
const results = tags.map(tag => ({
id: index + 1,
title: tag.tags.title || undefined,
artist: tag.tags.artist || undefined
}));
// results.sort((a, b) => a.id - b.id) - not necessary given .map() keeps the order
this.dispatchEvent(new CustomEvent('tracks-selected', {
detail: results
}))
});
我正在使用 bluebird 的 Promise.map
。在调度包含对象数组的事件之前,我试图等待所有承诺都解决。
readFiles() {
const fileArray = Array.from(this.fileSelectInput.files)
const promises = []
window.Promise.map(fileArray, (file, index) => {
return window.jsmediatags.read(file, {
onSuccess: tag => {
promises.push({
id: index + 1,
title: tag.tags.title || undefined,
artist: tag.tags.artist || undefined
})
promises.sort((a, b) => a.id - b.id)
console.log('I should be first')
}
})
}).then(() => {
console.log('I should be second')
this.dispatchEvent(new CustomEvent('tracks-selected', {
detail: promises
}))
}
}
我 运行 遇到 I should be second
在 I should be first
之前打印到控制台的问题。事件调度的 detail: promises
包含一个空数组。
您可能正在寻找
const fileArray = Array.from(this.fileSelectInput.files);
window.Promise.map(fileArray, file => {
return new Promise((resolve, reject) => {
window.jsmediatags.read(file, {
onSuccess: resolve,
// also pass reject as an error handler if jsmediatags supports that
});
});
}).then(tags => {
const results = tags.map(tag => ({
id: index + 1,
title: tag.tags.title || undefined,
artist: tag.tags.artist || undefined
}));
// results.sort((a, b) => a.id - b.id) - not necessary given .map() keeps the order
this.dispatchEvent(new CustomEvent('tracks-selected', {
detail: results
}))
});