首页 > 解决方案 > 打字稿将异步函数结果分配给变量

问题描述


我有一个问题,我知道那里有非常相似的问题。我也尝试了他们的建议。但我无法解决我的问题,所以我现在问。首先,由于我的打字稿版本,顶级等待无法正常工作。请不要建议。

我正在尝试根据数据库记录设置对象的字段。我将检查我的对象的最后 10 分钟记录,然后如果它们相同,我将设置一个字段 isSame = true 否则 isSame = false。我正在通过将它们写入 .txt 文件来实现它,它工作正常。但我不想创建长 txt 文件,所以我会用 db 记录来做。
创建对象后,我将对象发送给客户端。我在我的 ts 文件中设置我的对象字段,如虚拟代码:

object.id = 3;
object.prm = 5;
object.isSame = checkSame(); //checkSame is my function which decide whether true or not with log file
sendToClient(object);

但是当我转换它时,数据库读取是异步函数。所以我的变量将永远是未定义的。为了显示我的问题,我创建了一个具有相同问题的虚拟项目。
这是 main.ts 行:

myObject.type = 0;
var persons = readDb("test");
myObject.persons = persons;

这是数据库中的功能:

export function readDb(personName: string) {
    getConnection().connect().then(connection => {connection.getRepository(Person).find({name: personName})
        .then(persons => {
            console.log(persons);
            return persons;
        }
        )});
}

如果我这样做,我可以在 readDb 函数中获取人员,但不能在主程序的流程中获取人员。我需要主程序流程中的返回值。我试过了:

var persons = null;
async function test() {
    const result = await readDb("java");
    persons = result;
  }

console.log(persons);

但是人仍然是空的。我怎样才能做到这一点?我需要在主程序流上分配我的变量。我已经在我的异步函数上访问了它,但我无法返回它。(我尝试返回 Person[],任何等结果仍然相同)如何在主程序的流程中获取异步函数返回值以将其分配给变量?

标签: typescriptasynchronouspromisetypeorm

解决方案


您的readDb函数不返回任何内容。你await为它返回undefined。这应该做的工作:

export function readDb(personName: string) {
  return getConnection().connect()
    .then(connection => {
      connection.getRepository(Person).find({ name: personName })
        .then(persons => {
          console.log(persons)
          return persons
        })
    })
}

或者使用 async/await 风格:

export async function readDb(personName: string) {
  const connection = await getConnection().connect()
  const persons =  await connection.getRepository(Person).find({ name: personName })
  console.log(persons)
  return persons
}

推荐阅读