javascript - Resolve a function that uses Promise
问题描述
I have the following async function
export default async function getUserNames(id: string[]): Promise<string[]> {
let userNames: string[] = [];
// We do some stuff here like calling a service, etc...
return userNames;
}
On a different typescript file, I am importing the getuserNames function and trying to call it like this:
const promiseResult = getUserNames(idList)
.then(result => {
return result;
})
.catch(error => {
return undefined;
});
if (promiseResult) {
// Do something else here.
}
However, the promiseResult type is of Promise instead of string[] which is what I am expecting. How can I call the getuserNames function and when it is done, the actual string[] is returned to the promiseResult variable?
EDIT Is it accepted to do something like this?
let varB: string[];
const promiseResult = getUserNames(idList)
.then(result => {
varB = result;
})
.catch(error => {
varB = undefined;
});
if (varB) {
// Do something else here.
}
Lastly, please notice that the function that calls getUserNames is not defined as async and I can't change that.
解决方案
如果您想访问 promise 解析为的值,您唯一的选择是
1) 使用 promise 的 .then 回调
getUserNames(idList)
.then(result => {
// Do something else here.
})
2)将代码放在异步函数中并使用 await 关键字:
async function someFunction () {
const result = await getUserNames(idList);
// Do something else here.
}
请注意,由于所有异步函数都返回 Promise,因此在此示例中 someFunction 将返回 Promise。
推荐阅读
- java - beans.xml 拦截器无效,发现模式“注释”
- flutter - 包装类不包装小部件
- sql-server - 安装 SQL Server Management Studio 17.6、18.5 代码时出错:0x800b0003:
- vb.net - 无法让 CefSharp Chromium 网络浏览器在目标 PC 上运行
- sql - 以小时为单位的日期差异
- javascript - 在传单上实时显示本地 .txt 文件
- javascript - 创建滑块以显示多个图像
- discord.py - 有没有办法从 discord.py 获取自定义状态消息?
- python-3.x - 为什么 Python pandas 仅限于 numpy.datetime64[ns]?
- spring - SpringBoot应用程序销毁ApplicationContext后如何调用方法