我对 JS 还很陌生。我正在使用具有异步回调的第三方库。问题是我需要在处理下一个回调之前完整运行该函数。我正在使用一种名为 tus.io 的上传协议,并且需要一次处理一个上传。
async onUploadCreate(req, res, uploadMetadata) {
/* I need to check the metadata is valid by using an internal js file */
//...
/* Then I need to check the user is logged in by calling a third-party endpoint using axios*/
//...
/* Then I check the Mongo db for existing uploadId
//...
// if it's not there, create some entries in another db and add the uploadId to mongo
//If it is there, get some IDs in mongo, which I append to another db
}
如你所见,我需要做一些事情。我这样做是因为在这种情况下,不存在上传会话的概念;每个文件都是独立上传的。我一直通过一次上传一个文件来测试它。当我使用多个文件时,它到处都是。
有没有办法可以在 JavaScript 中实现这一点?我知道这可能会对性能产生影响,因此我愿意接受有关如何实现此目标的建议。
编辑:根据评论建议,我尝试等待使用 axios 和 mongo lib 的函数,但这似乎没有什么区别。这是完整的函数调用:
async onUploadCreate(req, res, upload) {
/* Check the metadata */
const {ok, expected} = await common.validateMetadata(upload);
if (!ok) {
const body = `Expected "${expected}" in "Upload-Metadata" but received "${upload.metadata}"`;
throw {status_code: 500, body};
} else
logger.info(`Metadata is ok!`);
/* Check the user is logged in */
const userAuthorised = await catalogue.getSession(upload.metadata.userSession);
if (!userAuthorised) {
const body = `User not authorised`;
logger.info(`User with session id: "${upload.metadata.userSession}" not authed`);
throw {status_code: 401, body};
} else
logger.info(`User with session id: "${upload.metadata.userSession}" is logged in`);
/* Create the items in the catalogue and mongo db for tracking upload session*/
// check the mongo db for existing uploadId
const result = await mongo.getUploadIdInDB(upload.metadata.uploadId);
if (result == null) {
logger.info(`Upload ID: "${upload.metadata.uploadId}" not found in mongodb`)
// create a dataset in catalogue
let dataset = await catalogue.createDataset(upload.metadata);
// then create the datafiles in catalogue
let datafile = await catalogue.createDatafile(dataset, upload.id, upload.size, upload.metadata);
// then add the id in mongo
await mongo.createUpload(upload.metadata, dataset, datafile)
}
else {
logger.info(`Upload ID: "${upload.metadata.uploadId}" found in mongodb!`)
// create a new datafile to go this dataset
let datafile = await catalogue.createDatafile(result.datasetId[0], upload.id, upload.size, upload.metadata);
// then add the id of the nre datafile to the upload entry in mongo
await mongo.appendToUpload( result.datasetId, datafile)
}
logger.info(`Done processing upload file`)
return res;
},
例如我得到的输出是:
info: Metadata is ok! {"service":"upload-service"}
info: Metadata is ok! {"service":"upload-service"}
info: User with session id: "bb6190fb-369b-406e-8b64-b38bef644df6" is logged in {"service":"upload-service"}
info: User with session id: "bb6190fb-369b-406e-8b64-b38bef644df6" is logged in {"service":"upload-service"}
....
我希望它们交错的地方
因为该调用是我无权访问的异步回调,所以我无法
await
它。答案是消除应用程序存储任何状态的责任,将上游数据库对象的任何创建推送到前端或其他服务。这仅意味着 UI 必须连续调用 2 次,而不是一次。