2

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();

1
  • 1
    yes just return the data in the callback and use that line Commented Sep 29, 2018 at 19:53

3 Answers 3

1

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).

Sign up to request clarification or add additional context in comments.

3 Comments

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.
0

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

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.