Search code examples
javascriptecmascript-6ecmascript-2016

Awaiting function that resolves a promise with no arguments


I have a function that resolves a Promise without passing any arguments:

const checkUser = (user)=> {
    let promise = Parse.Promise();

    if(user.success){
        promise.resolve();
    } else {
        promise.reject("Error");
    }
}

The problem is that in all tutorials that I read, they assign the returning value to a variable, like this:

let response = await checkUser(user);

In the above case, can I just await for the promise without assigning the result to a variable or this is not recommended? For example:

...
await checkUser(user);
...

Solution

  • Yes, you can totally do that. JavaScript will still wait for the promise to resolve.

    Here is a modification of MDN's first example for await. It does not return a value but still waits for the Promise to resolve before running the code after await.

    function resolveAfter2Seconds() { 
      return new Promise(resolve => {
        setTimeout(resolve, 2000);
      });
    }
    
    (async function() {
      console.log(1)
      await resolveAfter2Seconds();
      console.log(2);
    })()