我想按常规顺序记录日志
(通话1,通话2,通话3)
但是结果.. call2,call3,call1 ...
我该怎么办?
我用了promise ..但是结果是一样的.. 这是一些代码
{
..
if (typeof files['images1'] !== 'undefined' && files['images1'].length > 0) {
convertToWebp(files['images1'])
console.log(2)
}
if (typeof files['images2'] !== 'undefined' && files['images2'].length > 0) {
convertToWebp(files['images2'])
console.log(2)
}
console.log(3)
res.send~
}
async function convertToWebp(files : MulterFile[]){
files.forEach(async function(file) {
await sharp(file.path).webp({quality:70}).toFile("some_rule", async (err, info) => {
await deleteFile(file.filename)
console.log(1)
})
})
/*
await Promise.all(files.map(async (file) => {
await sharp(file.path).webp({quality:70}).toFile("some_rule", async (err, info) => {
await deleteFile(file.filename)
console.log(1)
})
}))
*/
}
function deleteFile(image : string){
..
}
答案 0 :(得分:0)
尝试一下
async function convertToWebp(files : MulterFile[]) {
await Promise.all(files.map(async(file) => {
const info = await sharp(file.path).webp({quality:70}).toFile("some_rule");
if(info) {
const deleteFile = await deleteFile(file.filename)
console.log(1)
}
}))
}
答案 1 :(得分:0)
await在数组迭代功能(forEach,map等)中不起作用
您将必须编写普通循环,
(async()=>{
if (typeof files['images1'] !== 'undefined' && files['images1'].length > 0) {
await convertToWebp(files['images1'])
console.log(2)
}
if (typeof files['images2'] !== 'undefined' && files['images2'].length > 0) {
await convertToWebp(files['images2'])
console.log(2)
}
console.log(3)
res.send~
}
})()
async function convertToWebp(files : MulterFile[]){
for(let i in files){
const file = files[i]
await sharp(file.path).webp({quality:70}).toFile("some_rule")
await deleteFile(file.filename)
}