Async/Await on return variable from promise

async/await vs promises
async/await fetch
async/await try catch
wait for promise to resolve
await inside promise
nodejs async/await
javascript promise
await javascript

I've got into the pattern of using async await in my aws nodejs lambda functions, and I common thing I run into is the need to await the result of a promise and use the response in the next async/await promise, and sort of repeat this pattern until I've run all my logic.

let userId;
await GetUserId({AccessToken: headers.accesstoken}).then(function(res){
 userId = res;
},function(err){

});

let username;
await GetUserName(userId).then(function(res){
 username = res;
},function(err){

});

Is there anyway I can declare and assign userId a value in the same line as invoking the function.

sudo code:

let userId = await GetUserId().then(()=>{ //bubble response up to userId })

The reason I'm asking is that it just sort of messing/wrong initializing a variable separately. Maybe I need a different pattern, or it's just something I'll have to live with.

Solution

var ExampleFunction = async() => {

  try {
    const userId = await GetUserId('token');
    const username = await GetUserName(userId);
    console.log(`userId: ${userId}`);
    console.log(`username: ${username}`);
  } catch (err) {
    console.log(err);
    console.log(`Exit Function`);
  }

  function GetUserId(token) {
    return new Promise(function(resolve, reject) {
      if (!token)
        reject('no token');
      resolve('ID');
    });
  }

  function GetUserName(userId) {
    return new Promise(function(resolve, reject) {
      if (!userId)
        reject('no userId');
      resolve('NAME');
    });
  }

}

ExampleFunction();

The await is supposed to replace the then syntax (except you really need to distinguish fulfillment from rejection with it). The await expression either throws the rejection reason as an exception to catch, or results in the fulfilment value of the promise. You can directly use that:

const userId = await GetUserId({AccessToken: headers.accesstoken});
const username = await GetUserName(userId);

(I assume that it was unintentional that your current code ignored errors and continued with undefined values).

Async/await, Other values are wrapped in a resolved promise automatically. For instance, this function returns a resolved promise with the result of 1 ; let's test  The async keyword is used to create an asynchronous function that returns a promise that is either rejected or resolved. The promise is rejected when there is an uncaught exception thrown from that function or it is resolved otherwise. The await keyword is used inside an async function to pause its execution and wait for the promise.

The keyword await makes JavaScript wait until that promise resolves and returns its result.

let userId = await GetUserId({AccessToken: headers.accesstoken});

Async and Await in JavaScript, the extension to a promise., You can see above that running the code give you the output of a promise along with the value that is returned in the async function. You can also explicitly  This is a good thing™, and ought to improve code quality a whole lot. However, what a lot of people may have missed is that the entire foundation for async/await is promises. In fact every async function you write will return a promise, and every single thing you await will ordinarily be a promise.

if you assign the result of await to var it will be the promise resolve value

so you can

let userId = await GetUserId({AccessToken: headers.accesstoken});

and

let username = await GetUserName(userId);

PS. don't forget error handling using try/catch.

How to return the result of an asynchronous function in JavaScript, Perhaps internally it has a promise it needs to wait for, or a callback. Now this returns a promise, because it's an async function: asynchronousFunction() receives a new function as a parameter, which we call callback . Async functions return a Promise by default, so you can rewrite any callback based function to use Promises, then await their resolution. You can use the util.promisify function in Node.js to turn callback-based functions to return a Promise-based ones.

Async functions, Async return values. Async functions always return a promise, whether you use await or not. That promise resolves with whatever the async  The FromResult async method is a placeholder for an operation that returns a string. When GetLeisureHours is called from within an await expression in the ShowTodaysInfo method, the await expression retrieves the integer value (the value of leisureHours) that's stored in the task returned by the GetLeisureHours method.

await, The await operator is used to wait for a Promise. Returns the fulfilled value of the promise, or the value itself if it's not a Promise . Description. The await expression causes async function execution to pause until a Promise is settled (​that missing name after . operator · SyntaxError: missing variable name  Here, if you call foo, the returned promise will always wait one second, then either fulfill with "yay", or fulfill with "caught". Because we await the result of waitAndMaybeReject (), its rejection will be turned into a throw, and our catch block will execute. If waitAndMaybeReject () fulfills, we return its result.

async function, If the return value of an async function is not explicitly a promise, it will be of return values in Promise.resolve does not imply that return await  Even though getPromise is literally empty, it’ll still return a promise since it was an async function. If the async function returns a value, that value will also get wrapped in a promise. That means you’ll have to use .then to access it.

Comments
  • yes just return the data in the callback and use that line
  • What do you think the best way to handle variable declaration is given these will need to be individually wrapped in a try catch blocks in order to have control over when my lambda exits. I don't want to run anymore code once one of these fails since I won't have the dependent info to execute the rest of the logic in the function.
  • You don't have to wrap them individually. If the awaited promise rejects, an exception will be thrown, and as usual no further code will run. The exception bubbles until it is caught somewhere.
  • This is much cleaner, thank you. I put my solution in the question.