将异步函数结果分配给变量的打字稿

时间:2021-04-06 14:06:02

标签: typescript asynchronous promise typeorm


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

我正在尝试根据数据库记录设置对象的字段。我将检查我的对象的最后 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 仍然为空。我怎样才能做到这一点?我需要在主程序流上分配我的变量。我已经在我的异步函数上访问了它,但我无法返回它。 (我尝试返回 Person[],任何等结果仍然相同) 如何在主程序流中获取异步函数返回值以将其分配给变量?

1 个答案:

答案 0 :(得分:0)

您的 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
}