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

문제

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?

도움이 되었습니까?

해결책

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...')); 
}

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top