gpt4 book ai didi

javascript - 如何在 Feathers 中创建异步超时错误处理程序?

转载 作者:行者123 更新时间:2023-12-02 22:16:04 25 4
gpt4 key购买 nike

如何创建一个异步函数超时错误处理程序作为驻留在服务文件中的 Feather 中的钩子(Hook)来处理钩子(Hook)中的 Promise?

按照@Bergi on my previous question的建议专门创建的帖子

If you are looking to implement a generic async-function timeout (for promises failing to fulfill for whatever reason) as a featherjs hook, you might want to ask a new (different!) question about specifically that.

我需要一个将添加到database.hooks.js的函数文件(如示例文档中的错误处理程序)将处理由类似于 get-database-by-id.js 的钩子(Hook)引起的异常(导致超时),而无需更改 get-database-by-id.js 中的代码:

按 id 获取数据库

const errors = require('@feathersjs/errors');

module.exports = function (options = {}) {
return async context => {
let promise = new Promise((resolve,reject) => {
context.app.service('database').find({
query: {"id":context.data.id}
}).then(result => {

resolve(result.data[0].data)
// console: error: Unhandled Rejection at: Promise
//browser: hangs

});
});
let result = await promise;
if (result) {
return context;
}

};
};

database.hooks.js(使用文档中的错误处理程序示例,不适用于 Promise)

const { authenticate } = require('@feathersjs/authentication').hooks;

const getDatabaseById = require('../../hooks/get-database-by-id');

const errors = require('@feathersjs/errors');

const errorHandler = ctx => {
if (ctx.error) {
const error = ctx.error;
if (!error.code) {
const newError = new errors.GeneralError("server error");
ctx.error = newError;
return ctx;
}
if (error.code === 404 || process.env.NODE_ENV === "production") {
error.stack = null;
}
return ctx;
}
};


module.exports = {
before: {
all: [ authenticate('jwt')],
find: [],
get: [],
create: [
getDatabaseById,
],
update: [],
patch: [],
remove: []
},

after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},

error: {
all: [errorHandler],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};

最佳答案

如果featherjs find返回一个promise,那么就没有必要将它包装成一个。

但我认为我理解这个问题的意思是,featherjs 已损坏,因为它不会拒绝或解决丢失的 id,并且您希望在合理的等待时间后强制解决。如果我理解正确的话,您可以使用 Promise.race() 实现自己的超时

// find with the given id, or reject after quitAfter milliseconds
async function findById(id, quitAfter) {
let timer = new Promise(function(resolve, reject) {
setTimeout(reject, quitAfter, 'timeout exceeded');
});
let query = context.app.service('database').find({
query: { "id": id }
});
return Promise.race([timer, query]);
}

关于javascript - 如何在 Feathers 中创建异步超时错误处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59384034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com