简体   繁体   中英

How to reject a promise in a function of both sync and async code?

In my class I got a function that contains both sync and async code, something like:

export class SomeClass(){
    constructor(){
    }

    foo(a: SomeDataClass): Promise<void>{
        if(!a){
            throw new Error('a is undefined');
        }

        return doSomething(a.value).then(()=>{
            console.log('done');
        }).catch((error)=>{
            throw error;
        });
    }
}

export class SomeDataClass(){
    public value: number;
    public name: string;

    constructor(){
    }
}

Throwing the follow errors in the catch part would raise the catch for the user of foo function. but the first throw (in the if section) wont, in order to catch this i would have to surroun the use of foo within a try/catch.

How could i raise an error for the returned promise if i throw it not within a then section? (Without using bluebird and rejecting a Resolver )

Please let me know if something is missing.

Thanks in advance for the help.

So I have found out there is a reject function on the Promise which actually does exactly what i was looking for, it raises an error for the function its used in as a Promise error and not like a regular throw to catch within a try/catch .

Returning this does the same a throwing an error in a Promise.then chains

foo(a: SomeDataClass): Promise<void>{
    if(!a){
        return Promise.reject('a is undefined'); //<----- Promise.reject
    }

    return doSomething(a.value).then(()=>{
        console.log('done');
    }).catch((error)=>{
        throw error;
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM