She*_*een 2 javascript asynchronous node.js
我正在运行这个异步函数:
async function getIngress(namespace) {
try {
const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
return result.body.items[0].spec.rules[0].http.paths[0].path;
} catch (e) {
console.error(e.response.body);
}
}
console.log(getIngress(argument);
Run Code Online (Sandbox Code Playgroud)
控制台日志只打印一个承诺。有没有一种方法可以像我尝试的那样在函数之外访问承诺的返回值?
小智 5
是的你可以!我给你三个方法:
使用异步函数
async function logPromiseResult() {
console.log(await getIngress(argument));
}
Run Code Online (Sandbox Code Playgroud)
使用 .then 回调
getIngress(argument).then(result => console.log(result));
Run Code Online (Sandbox Code Playgroud)
或者您只需更改该函数定义即可
async function getIngress(namespace) {
let response;
try {
const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
response = result.body.items[0].spec.rules[0].http.paths[0].path;
} catch (e) {
console.error(e.response.body);
}
console.log(response);
return response;
}
Run Code Online (Sandbox Code Playgroud)
希望这就是您所需要的并且对您有帮助!
| 归档时间: |
|
| 查看次数: |
4881 次 |
| 最近记录: |