0

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.

2
  • An async function does always return a promise. If you don't return anything explicitly, it's a promise of undefined. If you return a promise, it's a promise of whatever that promise resolves to. Otherwise it's a promise of whatever you return. Commented Apr 24, 2020 at 15:10
  • Don't pass a callback, just return doSomeWork(response); then when you call it, do upload(param).then(response => { console.log(response); }); instead. Commented Apr 24, 2020 at 15:11

1 Answer 1

4

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.