从打字稿节点中的异步等待中获取未定义
getting undefined from async await in typescript node
用例:
我正在尝试使用 Node 和打字稿在亚马逊 QLDB 中插入一条记录。
我能够成功插入 record/document,它 return 是 return.
中的 documentID
有 2 个控制器:EntityController 和 CommonController
-EntityController 扩展 CommonController
-EntityController 具有获取 req 对象并将其转换为模型对象的代码以及从 CommonController 扩展而来的调用 insert() 函数的代码。
问题
我试图将该 documentID 一直传播到我的 API 调用,但不知何故我在 EntityController 中变得不确定。
而我能够在 CommonController 中打印 documentID。
我不确定为什么当我清楚地return输入一个值时我会变得不确定。
const CommonController = require("../template/controller");
import { Request, Response } from 'express';
const tableName:string = "entities";
const EntityModel = require("./model")
class EntityController extends CommonController {
async insertEntitiy(req:Request,res:Response) {
async insertEntitiy(req:any,res:any) {
console.log(req);
console.log("===========");
console.log(req.body);
let entity = new EntityModel();
entity.balance = req.body.balance;
entity.firstName = req.body.firstName;
entity.lastName = req.body.lastName;
entity.email = req.body.email;
try {
let documentIds = await this.insert(tableName,entity);
console.log("--------- inside insertEntity fiunction()---------");
console.log(documentIds);
console.log("------------------");
res.status(200).send(documentIds[0]);
} catch (error) {
console.error(`error in creating Entity: ${error}`);
res.status(500).send({ errMsg: `error in creating Entity: ${error}` });
}
}
}
module.exports = new EntityController();
import { createQldbWriter, QldbSession, QldbWriter, Result, TransactionExecutor } from "amazon-qldb-driver-nodejs";
import { Reader } from "ion-js";
import { error, log } from "../qldb/LogUtil";
import { getFieldValue, writeValueAsIon } from "../qldb/Util";
import { closeQldbSession, createQldbSession } from "../qldb/ConnectToLedger";
module.exports = class Conroller {
async insert(tablename:string, object:any): Promise<Array<string>> {
let session: QldbSession;
let result:Array<string>;
try {
session = await createQldbSession();
await session.executeLambda(async (txn) => {
result = await this.insertDocument(txn,tablename,object);
console.log("---------result inside insert fiunction()---------");
console.log(result);
console.log("------------------");
return (Promise.resolve(result));
})
} catch (e) {
error(`Unable to insert documents: ${e}`);
return(["Error"]);
} finally {
closeQldbSession(session);
}
}
/**
* Insert the given list of documents into a table in a single transaction.
* @param txn The {@linkcode TransactionExecutor} for lambda execute.
* @param tableName Name of the table to insert documents into.
* @param documents List of documents to insert.
* @returns Promise which fulfills with a {@linkcode Result} object.
*/
async insertDocument(
txn: TransactionExecutor,
tableName: string,
documents: object
): Promise<Array<string>> {
const statement: string = `INSERT INTO ${tableName} ?`;
const documentsWriter: QldbWriter = createQldbWriter();
let documentIds: Array<string> = [];
writeValueAsIon(documents, documentsWriter);
let result: Result = await txn.executeInline(statement, [documentsWriter]);
const listOfDocumentIds: Reader[] = result.getResultList();
listOfDocumentIds.forEach((reader: Reader, i: number) => {
documentIds.push(getFieldValue(reader, ["documentId"]));
});
console.log("---------documentIds---------");
console.log(documentIds);
console.log("------------------");
return (documentIds);
}
}
输出:
----------documentIds---------
['4o5UZjMqEdgeENqbP9l7Uhz']
------------插入函数()中的结果---------
['4o5UZjMqEdgeENqbP9l7Uhz']
--------- insertEntity 函数() 内部---------
未定义
正如@daniel-w-strimpel 在评论中指出的那样,您的插入方法 return 仅在 catch 部分。
试试这个:
insert(tablename:string, object:any): Promise<Array<string>> {
let session: QldbSession;
let result: Array<string>;
try {
session = await createQldbSession();
return session.executeLambda(async (txn) => {
result = await this.insertDocument(txn,tablename,object);
console.log("---------result inside insert fiunction()---------");
console.log(result);
console.log("------------------");
return result;
})
} catch (e) {
error(`Unable to insert documents: ${e}`);
return(["Error"]);
} finally {
closeQldbSession(session);
}
}
...
在return session.executeLambda
你return的承诺。
在return result;
你return的实际值。
更多关于这里的承诺:https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html
用例: 我正在尝试使用 Node 和打字稿在亚马逊 QLDB 中插入一条记录。 我能够成功插入 record/document,它 return 是 return.
中的 documentID有 2 个控制器:EntityController 和 CommonController -EntityController 扩展 CommonController -EntityController 具有获取 req 对象并将其转换为模型对象的代码以及从 CommonController 扩展而来的调用 insert() 函数的代码。
问题 我试图将该 documentID 一直传播到我的 API 调用,但不知何故我在 EntityController 中变得不确定。 而我能够在 CommonController 中打印 documentID。
我不确定为什么当我清楚地return输入一个值时我会变得不确定。
const CommonController = require("../template/controller");
import { Request, Response } from 'express';
const tableName:string = "entities";
const EntityModel = require("./model")
class EntityController extends CommonController {
async insertEntitiy(req:Request,res:Response) {
async insertEntitiy(req:any,res:any) {
console.log(req);
console.log("===========");
console.log(req.body);
let entity = new EntityModel();
entity.balance = req.body.balance;
entity.firstName = req.body.firstName;
entity.lastName = req.body.lastName;
entity.email = req.body.email;
try {
let documentIds = await this.insert(tableName,entity);
console.log("--------- inside insertEntity fiunction()---------");
console.log(documentIds);
console.log("------------------");
res.status(200).send(documentIds[0]);
} catch (error) {
console.error(`error in creating Entity: ${error}`);
res.status(500).send({ errMsg: `error in creating Entity: ${error}` });
}
}
}
module.exports = new EntityController();
import { createQldbWriter, QldbSession, QldbWriter, Result, TransactionExecutor } from "amazon-qldb-driver-nodejs";
import { Reader } from "ion-js";
import { error, log } from "../qldb/LogUtil";
import { getFieldValue, writeValueAsIon } from "../qldb/Util";
import { closeQldbSession, createQldbSession } from "../qldb/ConnectToLedger";
module.exports = class Conroller {
async insert(tablename:string, object:any): Promise<Array<string>> {
let session: QldbSession;
let result:Array<string>;
try {
session = await createQldbSession();
await session.executeLambda(async (txn) => {
result = await this.insertDocument(txn,tablename,object);
console.log("---------result inside insert fiunction()---------");
console.log(result);
console.log("------------------");
return (Promise.resolve(result));
})
} catch (e) {
error(`Unable to insert documents: ${e}`);
return(["Error"]);
} finally {
closeQldbSession(session);
}
}
/**
* Insert the given list of documents into a table in a single transaction.
* @param txn The {@linkcode TransactionExecutor} for lambda execute.
* @param tableName Name of the table to insert documents into.
* @param documents List of documents to insert.
* @returns Promise which fulfills with a {@linkcode Result} object.
*/
async insertDocument(
txn: TransactionExecutor,
tableName: string,
documents: object
): Promise<Array<string>> {
const statement: string = `INSERT INTO ${tableName} ?`;
const documentsWriter: QldbWriter = createQldbWriter();
let documentIds: Array<string> = [];
writeValueAsIon(documents, documentsWriter);
let result: Result = await txn.executeInline(statement, [documentsWriter]);
const listOfDocumentIds: Reader[] = result.getResultList();
listOfDocumentIds.forEach((reader: Reader, i: number) => {
documentIds.push(getFieldValue(reader, ["documentId"]));
});
console.log("---------documentIds---------");
console.log(documentIds);
console.log("------------------");
return (documentIds);
}
}
输出: ----------documentIds---------
['4o5UZjMqEdgeENqbP9l7Uhz']
------------插入函数()中的结果---------
['4o5UZjMqEdgeENqbP9l7Uhz']
--------- insertEntity 函数() 内部---------
未定义
正如@daniel-w-strimpel 在评论中指出的那样,您的插入方法 return 仅在 catch 部分。
试试这个:
insert(tablename:string, object:any): Promise<Array<string>> {
let session: QldbSession;
let result: Array<string>;
try {
session = await createQldbSession();
return session.executeLambda(async (txn) => {
result = await this.insertDocument(txn,tablename,object);
console.log("---------result inside insert fiunction()---------");
console.log(result);
console.log("------------------");
return result;
})
} catch (e) {
error(`Unable to insert documents: ${e}`);
return(["Error"]);
} finally {
closeQldbSession(session);
}
}
...
在return session.executeLambda
你return的承诺。
在return result;
你return的实际值。
更多关于这里的承诺:https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html