[英]nodejs enable async function return value in global scope
我需要將異步函數返回的值用於 get 請求。 這是我的代碼:
let pwd;
async function getSecret() {
const [version] = await smClient.accessSecretVersion({
name: pgpwd
});
const pwd = version.payload.data.toString();
console.log(`in ${pwd}`);
return pwd;
}
promise1 = getSecret().then((pwd) => console.log(`promise then ${pwd}`) );
console.log(promise1.then((pwd) => console.log(`promise1 ${pwd}`)));
console.log(`global scope pwd ${pwd}`);
app.get('/pwd', (req, res) => {
console.log(`get ${pwd}`);
res.send(`pwd = ${pwd}!`);
});
我收到了 promise.then 中的值,但它在全局范圍內未定義。
2020-09-20 11:27:00.909 > node index.js
2020-09-20 11:27:00.909
2020-09-20 11:27:02.152 GET200363 B2 sPostmanRuntime/7.26.5 https://nodejs1-
2020-09-20 11:27:03.379 get undefined
2020-09-20 11:27:03.445 in 123456
2020-09-20 11:27:03.445 promise then 123456
2020-09-20 11:27:03.445 promise1 undefined
2020-09-20 11:27:04.634 get undefined
您根本不需要全局變量。 使您的 GET 請求回調也async
,並await
回調中await
getSecret
函數的結果。
如果getSecret
是一個執行getSecret
的函數,那么你可以用一個閉包來包裹它,其中存儲pwd
值。然后當函數被調用時,它會檢查getSecret
之前是否被調用過並調用它。 或者當它之前被調用時只返回結果而不是再次調用getSecret
。
async function getSecret() {
const [ version ] = await smClient.accessSecretVersion({
name: pgpwd
});
const pwd = version.payload.data.toString();
return pwd;
}
function storePwd() {
let pwd = null;
return async function() {
if (pwd === null) {
pwd = await getSecret();
}
return pwd;
};
}
const getPwd = storePwd();
app.get('/pwd', async (req, res) => {
const pwd = await getPwd();
res.send(`pwd = ${pwd}!`);
});
這沒有什么神奇之處。 你只需要分配它:
let pwd; // global
// ...
getSecret().then((localPwd) => { // renamed to something different so that we
// don't shadow (hide) the global pwd
console.log(`promise then ${localPwd}`);
pwd = localPwd; // assign to global variable
})
就是這樣。 這只是一個變量賦值。 沒有比這更復雜的了。
當然,這樣做意味着在getSecret()
返回之前應用程序啟動的最初幾毫秒內,全局pwd
值仍然是未定義的。 如果您此時碰巧執行了 get 請求,您將獲得未定義的信息。 但在那之后,它將具有您期望的價值。 只要您接受此限制,我就看不出您在做什么有任何問題。
但是,如果您不希望您的進程響應該獲取請求,那么在getSecret()
返回之前,您不得定義獲取請求。 通常我會親自編寫這樣的代碼:
getSecret().then((pwd) => {
console.log(`promise then ${pwd}`);
// ALL other app logic such as `get` definitions
// are done inside the promise then:
app.get('/pwd', (req, res) => {
console.log(`get ${pwd}`);
res.send(`pwd = ${pwd}!`);
});
});
如果您不希望then
函數太長,您可以將應用程序邏輯封裝在另一個函數中。 這不是什么新鮮事,C/C++ 有這樣的main()
函數:
let pwd;
function init () {
app.get('/pwd', (req, res) => {
console.log(`get ${pwd}`);
res.send(`pwd = ${pwd}!`);
});
}
getSecret().then((localPwd) => {
console.log(`promise then ${localPwd}`);
pwd = localPwd;
init(); // start the app
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.