简体   繁体   中英

Async/Await on return variable from promise

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

关键字 await 使 JavaScript 等待直到该承诺解析并返回其结果。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM