【问题标题】:How to implement async-await or then-catch correctly in a function with jquery request to google drive api如何在带有 google drive api 的 jquery 请求的函数中正确实现 async-await 或 then-catch
【发布时间】:2020-11-24 09:15:14
【问题描述】:

我尝试实现这个异步上传功能,然后当它完成时,我用另一个功能在谷歌驱动器中搜索文件,这两个功能都可以正常工作,但问题是应用程序不等待上传功能完成。 这是代码。

使用函数

async save() {
      let dataRequest;
      await this.uploadFileGoogleDrive (this.files[0]);
      dataRequest= await this.listFilesGoogleDrive ("name='"+ this.file_Name +"'");
      dataRequest= dataRequest.files;
      console.log ("Data request= ", dataRequest);
      ....

上传功能

async uploadFileGoogleDrive (archivo) {
  const file = archivo;
  const fr = new FileReader();
  fr.readAsDataURL(file);

  let metadata = {
    'name': nombreArchivo,
    'parents':[this.folder_Id]
  };
  
  return fr.onload = function () {
    const boundary = "xxxxxxxxxx";
    let data = "--" + boundary + "\n";
    data += "Content-Type: application/json; charset=UTF-8\n\n";
    data += JSON.stringify(metadata) + "\n";
    data += "--" + boundary + "\n";
    data += "Content-Transfer-Encoding: base64\n\n";
    data += fr.result.split(",")[1] + "\n";
    data += "--" + boundary + "--";

    $.ajax({
      type: "POST",
      beforeSend: function(request) {
        request.setRequestHeader("Authorization", "Bearer" + " " + localStorage.getItem("accessToken"));
        request.setRequestHeader("Content-Type", "multipart/related; boundary=" + boundary);
      },
      url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
      success: function (data) {
          console.log("Success= ", data);
      },
      error: function (error) {
          console.log(error);
      },
      async: true,
      data: data,
      cache: false,
      processData: false,
      timeout: 60000
    });
  };  
},

我不知道为什么等待不起作用,我尝试使用等待而不是返回,但给我这个错误“赋值表达式中的左侧无效”。

感谢您的任何建议,并感谢您抽出宝贵时间。

【问题讨论】:

    标签: javascript jquery async-await google-drive-api


    【解决方案1】:

    在您的函数 uploadFileGoogleDrive(archivo) 中,根据此更改您的代码:

    return fr.onload = async function () {
        const boundary = "xxxxxxxxxx";
        let data = "--" + boundary + "\n";
        ...
    
        await $.ajax({
            ...
        });
     };
    

    这将等待 ajax 调用完成,然后再执行进一步的代码。

    您可以在此处阅读有关使用 ajax 的 async/await 的更多信息: https://petetasker.com/using-async-await-jquerys-ajax

    【讨论】:

    • Thaks 但我已经尝试过了,但它不起作用return fr.onload = async function () {await $.ajax({
    猜你喜欢
    • 2021-03-01
    • 2021-04-10
    • 1970-01-01
    • 2018-07-05
    • 2018-01-28
    • 2020-01-02
    • 1970-01-01
    • 2020-02-24
    相关资源
    最近更新 更多