首页 > 解决方案 > 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.

标签: javascriptnode.jstypescriptpromise

解决方案


如果您想访问 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。


推荐阅读