Home > Net >  I can't get fetch to work with async/await
I can't get fetch to work with async/await

Time:08-20

I'm starting with Javascript, I am trying to make a fetch behave synchronously. I need that after calling a function that ends up calling the fecth to process the result.

async function _send_sync_command(command) {
  const response = await fetch("http://localhost:5700"   "/ext", {
  method: "POST",
  headers: {
        "Content-type": "application/json; charset=UTF-8"
    },
  body: JSON.stringify(command)
  });

  const data = await response.json();
    return data;
}

function send_command(command) {
  this._send_sync_command(command)
  .then((data) => {
    return data;
  })
}


function DownloadToFP(star_cmd, next_cmd, end_cmd) {
  var json_out = {};
  json_out.data_0 = "";
  json_out.data_1 = "";
    
  // Start download command
  var response = this.send_command(star_cmd);

  // I need this to run after all promises are resolved !!!

  if (response.fields.length > 0) {
    json_out.data_0 = response.fields[0];
  }
}

CodePudding user response:

You need to await the _send_sync_command function to stop the execution of the function at this point, and return back when all promises are resolved.

Also, I don't think you need send_command function.

UPDATE

as @danh suggests to return json_out from DownloadToFP function.

async function _send_sync_command(command) {
  const response = await fetch("http://localhost:5700"   "/ext", {
  method: "POST",
  headers: {
        "Content-type": "application/json; charset=UTF-8"
    },
  body: JSON.stringify(command)
  });

  const data = await response.json();
    return data;
}


async function DownloadToFP(star_cmd, next_cmd, end_cmd) {
  var json_out = {};
  json_out.data_0 = "";
  json_out.data_1 = "";
    
  // Start download command
  var response = await this._send_sync_command(star_cmd);

  // I need this to run after all promises are resolved !!!

  if (response.fields.length > 0) {
    json_out.data_0 = response.fields[0];
  }
  return json_out
}

  • Related