Typescipt。等待代码执行,直到函数完成执行

时间:2017-09-07 02:40:51

标签: typescript

我是打字稿的新手。

我有一个调用函数的代码,如下所示:

this.getAllOptions(questionID);
console.log("++++++++++++++++++++++++++++++++");
console.log(this.result);

该函数非常简单,它调用一个返回对象数组的服务。从返回的数据中,我只需要" item.Content"以字符串格式,如下所示。

result: string;
getAllOptions(question_ID){

    this.result = "";

    this._service.getOptionsQuestion(question_ID)
        .subscribe( data => {
            data.forEach(item => {
            console.log(item.Content);
            this.result += item.Content;
            });
        });
}

但问题是,调用函数后的代码" getAllOptions()"先执行。我想在调用方法之后等待代码直到函数执行完毕。

这可能吗?

2 个答案:

答案 0 :(得分:1)

您需要等待数据到达。在调用" 'formatlistpat' 'flp' string (default: "^\s*\d\+[\]:.)}\t ]\s*") " ignore '3 ' by removing space in pattern let &formatlistpat='^\s*\d\+[\]:.)}\t]\s*' " ignore (\n3) or [\n3] or {\n3} by adding a preceding NOT match let &formatlistpat='\([\[({]\s*\n\)\@<!\_^\s*\d\+[\]:.)}\t]\s*' 完成后,在getOptionsQuestion中创建的observable尚未收到任何数据,因此您传递给getOptionsQuestion的回调尚未被调用。

有几种等待数据的方法,我个人更喜欢Typescript中的async / await语法,使代码更具可读性:

subscribe

答案 1 :(得分:0)

我们也可以通过从getAllOptions函数返回一个promise来解决这个问题。

result: string;

getAllOptions(question_ID): Promise<void>{
    let resolveRef;
    let rejectRef;

    //create a new promise. Save the resolve and reject reference
    let dataPromise: Promise<void> = new Promise((resolve, reject) => {
        resolveRef = resolve;
        rejectRef = reject;
    });
    this.result = "";

    this._service.getOptionsQuestion(question_ID)
        .subscribe( (data: any) => {
            data.forEach(item => {
            console.log(item.Content);
            this.result += item.Content;
            });
            // resolve the promise once result is populated
            resolveRef(null);
        });

    //return promise created.
    return dataPromise;
}


// execute the console logs on then part of the promise returned by getAllOptions
this.getAllOptions(questionID).then( () => {
    console.log("++++++++++++++++++++++++++++++++");
    console.log(this.result);
});