What is the correct way to write a typescript method that expects a Promise but can return nothing if conditions aren't met?

StackOverflow https://stackoverflow.com/questions/23527645

Pregunta

Ok lets say I have a method as follows:

getSomethingImportant() : ng.IPromise<any> {
    if (!conditionsMet) { return; }
    return someApi.thatReturns.aPromise().then((response) => {
        // Normal stuff here
    });
}

Typescript gives a warning because return isn't returning anything, but thats because I want it to not run if the conditions aren't met (missing arguments or already running or whatever).

Should I create a promise and return it right away?

Should I ignore the error?

Change the return type?

¿Fue útil?

Solución

You can create a null-resolved promise and return it right away:

if (!conditionsMet) {
    return $q.when(null); 
}

Or you you perceive the situation when the conditions are not met as an error, you can return a rejected promise:

if (!conditionsMet) {
    return $q.reject(new Error('Conditions have not been met...')); 
}

Otros consejos

Function that returns a promise must never return anything else nor throw an exception. If you want to return something, return a promise resolved with the value you want to return and if you want to throw something, return a promise rejected with the error you want to throw.

Otherwise you are making the function extremely awkward to use.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top