从 Async/Await 求解未定义的最短路线
Shortest route to solve undefined from Async/Await
我正在尝试使用获取并输出环境变量的 Netlify 函数(修改后的 return-env.js)来保护我的 API 密钥。由于我的项目是在 vanilla JS 中,因此我必须从函数中获取密钥才能使用它。但这就是困难所在。
目前我有:
function getKey() {
(async ()=> {
const response = await fetch('/.netlify/functions/return-env')
const resObj = await response.json()
console.log(resObj);
return resObj;
})();
}
console.log("my key " + getKey())
const Airtable = require('airtable');
const base = new Airtable({apiKey: 'EXAMPLE-API-KEY'})
getKey()
始终 returns 未定义,如果在函数外登录,也会 resObj
。这里缺少什么?
getKey 将 return 未定义,因为您没有在函数调用中 returning 任何东西
function getKey() {
return (async ()=> {
...
})();
}
它现在 return 一个您可以链接或等待的承诺,等待将要求它在异步函数中。
如果你只是想 .then() 关闭它:
getKey().then((key) => {
// do something with the key object
}
我正在尝试使用获取并输出环境变量的 Netlify 函数(修改后的 return-env.js)来保护我的 API 密钥。由于我的项目是在 vanilla JS 中,因此我必须从函数中获取密钥才能使用它。但这就是困难所在。
目前我有:
function getKey() {
(async ()=> {
const response = await fetch('/.netlify/functions/return-env')
const resObj = await response.json()
console.log(resObj);
return resObj;
})();
}
console.log("my key " + getKey())
const Airtable = require('airtable');
const base = new Airtable({apiKey: 'EXAMPLE-API-KEY'})
getKey()
始终 returns 未定义,如果在函数外登录,也会 resObj
。这里缺少什么?
getKey 将 return 未定义,因为您没有在函数调用中 returning 任何东西
function getKey() {
return (async ()=> {
...
})();
}
它现在 return 一个您可以链接或等待的承诺,等待将要求它在异步函数中。
如果你只是想 .then() 关闭它:
getKey().then((key) => {
// do something with the key object
}