javascript – Return a function to execute – Typescript

Question:

I have a situation where I would like to generate an engine that executes an async function and executes a successful callback in the try and an error in the catch, and the responsibility of these callbacks is to send a res.send() in Express.

Motor code:

public async runAsyncFunction(asyncFunction: Promise<any>, 
   errorCallback: () => Response, 
   successCallback?: (any) => Response) {

    try {

        const data = await asyncFunction;

        if (!successCallback) {
            return data;
        }

        return successCallback(data);

    } catch (error) {
        return errorCallback();
    }
}

Callback Functions Code

export class ResponseHandler {

public successResponse(responseModel: any, res: Response) {
    return () => res.status(statusCode.success_ok).send(responseModel);
}

public unauthorizedResponse(res: Response, responseModel: ResponseModel, errorMessage: string) {

    responseModel.message = errorMessage;

    return () => res.status(statusCode.client_error_unauthorized).send(responseModel);
}

}

Invocation in the controller

const userInfoResponse = await this.asyncHandler.runAsyncFunction(this.idmService.getToken(access_token),
        this.responseHandler.unauthorizedResponse(res, modelResposta,
            'mensagem de erro'));

The error I'm getting is this:

Error: Can't set headers after they are sent.

It cost!!

Answer:

You can use the .catch() .then() .catch() .then() .catch() of promises Encapsulates the promise that comes in the parameter and returns a new promise, then you don't even need the callbacks. These snippets of code are a little confusing but I believe it is more or less that.

export class ResponseHandler {

    public successResponse(responseModel: any, res: Response) {
        return res.status(statusCode.success_ok).send(responseModel);
    }

    public unauthorizedResponse(res: Response, responseModel: ResponseModel, errorMessage: string) {

        responseModel.message = errorMessage;

        return res.status(statusCode.client_error_unauthorized).send(responseModel);
    }
}
public async runAsyncFunction(asyncFunction: Promise<any>) {
    const pr = new Promise((resolve, reject)=>{
        try {
            const data = await asyncFunction;
            resolve(data)
        } catch (error) {
            reject(error)
        }
    })

    return pr
}

Then your controller does something like this

const userInfoResponse = await this.asyncHandler.runAsyncFunction(this.idmService.getToken(access_token))
            .then(data=>console.log('sucesso'))
            .catch(erro=>this.responseHandler.unauthorizedResponse(res, modelResposta,'mensagem de erro'))
Scroll to Top