如何在循环体中执行异步代码后开始执行一些代码?

时间:2017-09-16 18:26:59

标签: javascript

例如,这段代码写道:"我在这里!"然后" 0,1,2,3 ..."

private currentSelectedVersionData = new BehaviorSubject<object>(null);
currentSelectedVersion$ = this.currentSelectedVersionData.asObservable(); 

// Call next to let our subscribers know about the currently selected version
updateCurrentSelectedVersion(version: object) {
    this.currentSelectedVersionData.next(version);
}

// Call to DB
fetchMapVersions(TargetID) {
    return new Promise((resolve, reject) => {
        this._http.post(this.baseUrl + '/fetchMapVersions', { "targetID": TargetID }, { "headers": this.headers })
            .map((result: Response) => result.json())
            .subscribe((results) => resolve(results));
    });
};

如何从循环中获取结果,然后执行下一部分代码?获得: &#34; 0,1,2,3 ... 10&#34;然后&#34;我来了!&#34;?

1 个答案:

答案 0 :(得分:4)

您可以将异步代码包装在promise中,然后使用Promise.all()等待结果。然后在

中打印“Here am I”

function A(i){
    return new Promise((resolve, reject) => {
            setTimeout(function(){
                resolve(i);
            }, 2000);

    })
}
let promiseArray = [];
for(let i=0; i<=10; i++) {
    //some async code
    promiseArray.push(A(i));
}

Promise.all(promiseArray).then((result) => {
    console.log(result);
    console.log("Here I am!");
})