So I have the following problem:
Given a key I will get a function from a dictionary, this function can be async or normal function. But when I put the await keyword before func the compiler complains:
TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'Promise ' has no compatible call signatures.
How could I solve this issue? A switch would be the only solution?
Simple example:
function example(aux: string){
return string
}
function async main(key, ...args): Promise<Boolean>{
dictionary = {
"example": example
}
let func = dictionary[key]
if (func instanceof Promise) { // If the function is a promise we wait
let result = await func(...args) //<-- PROBLEM HERE
} else {
let result = func(...args)
}
}
return result
Full example here:
export enum ValidatorsTypes {
EMAIL = 1,
EMAIL_IS_UNIQUE = 2
}
export function validEmail (text: any) {
const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return pattern.test(text) || 'Invalid e-mail.'
}
export async function isEmailUnique (text: any): Promise<boolean> {
let response = await UserService.list(1, 1, { 'email': text })
// if the number of matches is 0, then is unique
return response[1] === 0
}
export async function isAnswerValid (validatorsTypes: Array<ValidatorsTypes>, ...args: any) : Promise<boolean> {
let availableValidators = {
[ValidatorsTypes.EMAIL]: validEmail,
[ValidatorsTypes.EMAIL_IS_UNIQUE]: isEmailUnique
}
let results = []
for (let rule of validatorsTypes) {
let func = availableValidators[rule]
if (func instanceof Promise) { // If the function is a promise we wait
let result = await func(...args) //<-- PROBLEM HERE
results.push(result)
} else {
results.push(func(...args))
}
}
return !results.some(v => v === false)
}