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();
blackops
  • 2,205
  • 2
  • 18
  • 22

3 Answers3

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

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 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. – blackops Sep 29 '18 at 20:41
  • 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. – Bergi Sep 29 '18 at 20:47
  • This is much cleaner, thank you. I put my solution in the question. – blackops Sep 29 '18 at 21:00
0

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

let userId = await GetUserId({AccessToken: headers.accesstoken});
elad frizi
  • 655
  • 4
  • 9
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.

Mohammed Essehemy
  • 2,006
  • 1
  • 16
  • 20