skip to Main Content

I recently added jsdocs to my project and since then I have eslint telling me that
‘await has no effect on this kind of expression’

const result = await someAsyncFunction(); // await has no effect
console.log(result.property);

Removing the await keyword however has the effect that console tries to log before result has resolved.

I know that that eslint complains because someAsncyFunction does not return a promise itself but has async functions inside of it.

async function someAsyncFunction(){
  const response = await fetch('dataset');
  const anotherResponse = await fetch('anotherDataset')
  const merged = combineDatasets(response, anotherResponse)
  return merged;
}

Am I really supposed to wrap this function in another Promise?

async function someAsyncFunction(){
  return new Promise(async(resolve) => {
    ...
    resolve(merged);
  })
}

Ignoring the warning about ‘await having no effect’ works without problems – every time. How ever it makes me think that my approach and / or my understanding of promises is way of.

Maybe you could point me in the right direction here.

2

Answers


  1. Chosen as BEST ANSWER

    Every Async Function returns a promise

    And so does someAsyncFunction() by returning merged

    // await unwraps the promise 
    const result = await someAsyncFunction()
    

    So jsdoc complained because my comment was wrong

    /** @returns {Promise<customType>} */ 
    

  2. Am I really supposed to wrap this function in another Promise?

    No need to do so. This is done by your async function as it always returns a promise and resolves this promise on a successful/non-erroneous return:

    /**
     * Returns a promise that is successfully resolved as soon as "merged" is returned
     * @returns {Promise} You might want to also type the response: Promise<typeOfMerged>
     */
    async function someAsyncFunction() {
      const response = await fetch("dataset");
      const anotherResponse = await fetch("anotherDataset");
      const merged = combineDatasets(response, anotherResponse);
      return merged;
    }
    
    /**
     * await is needed if you want to use "merged".
     * If you want to work with the not yet resolved promise, you remove await here.
     */
    const result = await someAsyncFunction(); 
    console.log(result.property);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search