Jerzy Gruszka Jerzy Gruszka - 2 months ago 6
Javascript Question

Make typescript compiler not complain in Promise

This is probably easy, but I am quite new to promises. My code is not compiling, how to change that:

public static sendTestEvent(): Promise<boolean> {
let options: any = {headers: {'Content-Type': 'application/json'}};

this.modifyEvent().then(()=> {
return WebRequest.post(this.URI, options, JSON.stringify(this.eventToSend)).then((response) => {
return browser.sleep(Config.EVENT_PROCESS_TIMEOUT).then(() => {
console.log('resolved');
return Promise.resolve(true);
});
});
}, (err)=> {
return Promise.resolve(false);
});

}

public static modifyEvent(): Promise<boolean> {
let currentDate = new Date();

return new Promise<boolean>((resolve, reject) => {
console.log('Event modified');
resolve(true);
});
}


I get 'Return statement is required for non-void return type'

Answer

From what it looks like, you've told TypeScript that you're planning on returning something of type Promise<resolving to boolean> in the sendTestEvent method. It looks like there is no return statement found in that method. You should be able to fix this by returning the result of the .then method in that method.

public static sendTestEvent(): Promise<boolean> {
    let options: any = {headers: {'Content-Type': 'application/json'}};

    return this.modifyEvent().then(()=> {
//  ^^^^^^ return here
        return WebRequest.post(this.URI, options, JSON.stringify(this.eventToSend)).then((response) => {
            return browser.sleep(Config.EVENT_PROCESS_TIMEOUT).then(() => {
                console.log('resolved');
                return Promise.resolve(true);
            });
        });
    }, (err)=> {
        return Promise.resolve(false);
    });
}

public static modifyEvent(): Promise<boolean> {
    let currentDate = new Date();

    return new Promise<boolean>((resolve, reject) => {
        console.log('Event modified');
        resolve(true);
    });
}

That should fix the problem you're getting with the compiler.

Comments