Lucas Ramos
Lucas Ramos

Reputation: 348

How can I return a promise using the syntax of async/await?

So I am writing a function to upload a file and I am using a class Upload to do so. This class has a method called start that basically uploads the file to where I need it and return an object with the info of the file uploaded.

What I have done is that:

upload = async (param, onFinish) => {
  const upload = new Upload(param)
  let response = await upload.start()

  response = doSomeWork(response)

  onFinish(response)
}

And I use it like that:

upload(param, (response) => {console.log(response)} )

As you can see I am little confused with async function in javascript, I can see how that looks weird and one of the reasons is because I read everywhere that an async function should always return a promise.

But my question is how in this case could I return a promise if I need to do some work in the response first? what is the best way of implementing this so my async function is solid?

I have searched on Stack overflow and did not find a clear answer for my question I don't know if because i did not understand the answers correctly or because there isn't actually one but I hope that is not a duplicated question.

Upvotes: 0

Views: 41

Answers (1)

David
David

Reputation: 218818

If the function is async then it's already returning a Promise. Just return your value and it will be passed to that Promise:

upload = async (param) => {
  const upload = new Upload(param);
  let response = await upload.start();

  response = doSomeWork(response);

  return response;
}

Then you can await that result:

let response = await upload(param);
console.log(response);

Or use .then() on the returned Promise:

upload(param).then(response => console.log(response));

Upvotes: 4

Related Questions