javascriptnode.jsasync-awaitrequest-promise

JavaScript async function returns object Promise


I'm trying to figure out, how to return from JavaScript async function.

In Node.js application script.js I have a function:

  let result = getresult(input);

must be async function with /content tag in await fetch to insert, send msg: input value to server.js functions, and return result value. In script.js:

async function getresult(input) {
  const request = await fetch(
    `/content?${new URLSearchParams({
      msg: input,
    })}`
  );
  const serverRes = await request.json();
  console.log("Server response: ", serverRes );
  return serverRes ;
}

Chrome console successfully shows requested string Server response: {text: 'hello!'}, but return returns [object Promise]

I'm not sure, what I'm doing incorrectly.


Solution

  • let result = await getresult(input);
    

    You must await the result of your asynchronous function.