首页 > 解决方案 > 文件阅读器,使用 SparkMD5 检查图像的校验和,承诺

问题描述

我试图用 SparkMD5 库计算校验和,我使用 FileReader 从文件中正确读取 ArrayBuffer,并且我将 ArrayBuffer 传递给我的新函数:

countMD5Hash = function(data){
    return new Promise ((resolve,reject) => {
        let res = null;

        res = SparkMD5.ArrayBuffer.hash(data)

        if(res){
             resolve(res)
        }
    });
};

当我尝试像上面一样调用 countMD5Hash 时,它返回未定义,但是当我尝试在此函数中 console.log 而不解析时,它会记录正确的校验和。如何执行该功能将通过计数校验和解决响应?

标签: javascriptmd5filereader

解决方案


解决一个承诺不是返回一个值。要使用 resovled 值,您应该then像这样使用:

countMD5Hash(data).then(result => {
    // do whatever you want with the result
})

但是,如果你countMD5Hashasync函数中使用,你也可以await这样使用:

let handle = async function(data) {
    // this waits for the promise to fulfill (or reject! don't forget to deal with exceptions!)
    // and puts the resolved value into hash
    let hash = await countMD5Hash(data); 
    // do whatever you want with hash
}

推荐阅读