【问题标题】:Execute conditional statement after loop finishes in nodejs在nodejs中循环完成后执行条件语句
【发布时间】:2020-10-27 05:54:52
【问题描述】:

我有一个用于检查多个上传图像的纵横比的 for 循环,在完成循环后,我想检查 if else 条件中的比率以重定向用户。问题是在循环完成之前检查条件,我需要在检查条件之前完成循环。我发现异步虽然可能适合这里,但我对实现的最佳方法感到困惑,谁能给我解决方法来按顺序执行代码。

//check image ratio         
var validImageRatio = true;
for(i=0; i<req.files.propertyPhoto.length; i++){
    
    var tempFile = req.files.propertyPhoto[i].tempFilePath.replace(/\\/g, '/');
    var ratio;var width;var height;
    var acceptedRatio = 3;
    
    //get image ratio
    sizeOf(tempFile, function (err, dimensions) {
        width = dimensions.width;
        height = dimensions.height;
        ratio = width/height;
    });
    if (ratio < (acceptedRatio - 0.1) || ratio > (acceptedRatio + 0.1)) {
        validImageRatio = false;
        break;
    }
}
//if ratio invalid, redirect
if (!validImageRatio) {
    ...
}
//if ratio valid, upload
else{
    ...
}

【问题讨论】:

标签: node.js express async.js


【解决方案1】:

我猜你的意思,但一个 for 循环会在检查底部的条件之前完成,除非你包含一个“break”语句。 break 语句使 for 循环停止执行并继续执行。

【讨论】:

    【解决方案2】:

    由于您是异步执行检查,因此同步代码将首先运行。如果在 for 循环中使用 async/await,它将阻塞循环的每次迭代,使其运行速度变慢。您可以采用的方法是使用Promise.all 同时运行检查。

    const promises = req.files.propertyPhoto.map(prop => new Promise(resolve => {
        const tempFile = prop.tempFilePath.replace(/\\/g, '/');
        const acceptedRatio = 3;
    
        // get image ratio
        sizeOf(tempFile, function (err, dimensions) {
            const width = dimensions.width;
            const height = dimensions.height;
            const ratio = width / height;
            if (ratio < (acceptedRatio - 0.1) || ratio > (acceptedRatio + 0.1)) {
                return resolve(false);
            }
            resolve(true);
        });
    }));
    
    const result = await Promise.all(promises);
    
    if (result.some(r => r === false)) {
        // if any of the ratio is invalid, redirect
    
    } else {
        // else upload
        
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 2014-12-14
      • 2015-03-20
      • 1970-01-01
      • 2020-11-21
      • 2017-05-26
      • 2021-04-25
      相关资源
      最近更新 更多