使得打字稿编译器不会在Promise中抱怨

时间:2016-10-04 14:18:14

标签: typescript promise

这可能很容易,但我对承诺很新。我的代码没有编译,如何更改:

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

我得到'返回语句是非空返回类型'

2 个答案:

答案 0 :(得分:2)

从它看起来,你告诉TypeScript你计划在Promise<resolving to boolean>方法中返回sendTestEvent类型的东西。看起来在该方法中找不到返回语句。您应该能够通过在该方法中返回.then方法的结果来解决此问题。

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

这应该可以解决您在编译器中遇到的问题。

答案 1 :(得分:1)

您已将方法声明为返回承诺。所以回来吧:

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

return this.modifyEvent().then(()=> {
//...