【问题标题】:File Reader resolve before another function文件阅读器在另一个功能之前解析
【发布时间】:2019-11-13 23:02:45
【问题描述】:

我正在做一个文件上传器,您还可以在其中填写一些文本并选择文件。然后你按下提交按钮。我遇到的问题是所有其他部分都在文件读取器之前完成,因此变量未定义。

这是按钮的代码

<button class="btn btn-primary" onclick = "processFile();submitDiagnosis(this,`+index+`)">Submit</button>

如你所见,它调用函数过程文件并提交诊断

这是processFile(),即调用readFileAsync,使用promise来加载文件

    async function processFile(){
      try{
        const photo = document.getElementById("photo").files[0];
        const ipfs = window.IpfsApi('localhost', 5001) // Connect to IPFS
        let contentBuffer = await readFileAsync(photo);
        const buf = buffer.Buffer(contentBuffer) // Convert data into buffer
        ipfs.files.add(buf, (err, result) => { // Upload buffer to IPFS
          if(err) {
            console.error(err)
            return
          }
        window.enlace = `http://127.0.0.1:8080/ipfs/${result[0].hash}`
          })
      } catch(err){
        console.log(err);
      }
    }

那么readFileAsync就是这个

    function readFileAsync(file) {
      return new Promise((resolve, reject) =>{
        var reader = new FileReader();

        reader.onloadend =() => {
          resolve (reader.result);
        };

        reader.onerror = reject;

        reader.readAsArrayBuffer(file);

      });

    }

最后提交诊断是这个

  function submitDiagnosis(element,index)
    {
        urle = window.enlace;
        var table = document.getElementById("viewPatient");
        var patientAddress = table.rows[index].cells[1].innerHTML;

        //console.log(patientAddress);
        // var dropSelect = document.getElementById("ailmentsList"+patientAddress);
        var diagnosis = $("#ailmentsList"+patientAddress).val();
        diagnosis = parseInt(diagnosis);
        var diagnosed = ailmentsDict[diagnosis];
        var comments = document.getElementById("details").value;

        var oldRecords = $("#records"+patientAddress).html();

        var today = new Date();
        var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
        var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
        var dateTime = date+' '+time;


        var newRecords =
`Diagnosed By : ${docName}
Doctor's Public Key : ${key}
Time : ${dateTime}
Diagnosis : ${diagnosed}
Comments : ${comments}
File : ${urle}

`

我遇到的问题是,在提交诊断之前,我需要定义 var url 和链接的值,但我无法让它发生。就目前而言,我知道它是在提交诊断后定义的,就好像我第二次运行它时它确实显示为定义的那样。

【问题讨论】:

    标签: javascript asynchronous filereader synchronous


    【解决方案1】:

    我认为问题在于您同步调用了两个函数,但一个是异步的。只是一个建议,但您是否尝试过这样做?

    async function processAndSubmitFile() {
        await processFile();
        await submitDiagnosis();
    }
    

    所以你在点击按钮时调用该函数。

    希望对你有帮助!

    【讨论】:

    • 是的,我没有想到这一点。我实施了您的建议并在某些部分添加了承诺。现在它起作用了!谢谢
    • 很高兴我能帮上忙!快乐的黑客;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多