异步等待不起作用

时间:2018-08-01 13:48:55

标签: javascript async.js

因此,我在Javascript中具有以下功能,这些功能可通过查询服务器以获取项目列表及其详细信息来帮助设置我的projectDetailsList状态:

getProjectDetailsListHelper(){
    return new Promise(async (resolve) => {
        await Object.keys(this.state.projectList).map(function (pid) {
            this.getProjectDetails(pid);
        }, this);
        console.log("getProjectDetailsHelperEnd");
    });
};

async getProjectDetails(project_id)
{
    const server = URL;
    await request
        .get(`${server}/get_project_details_compact?project_id=${project_id}&user=${this.state.user}`)
        .endAsync()
        .then(res => {
            console.log("getProjectDetails Start: ", res.body);
            let projDetailsListNew = this.state.projectDetailsList;
            projDetailsListNew[res.body.project_id] = res.body;
            this.setState(this.setProjectDetailsList(projDetailsListNew));
            console.log("getProjDetails End:", this.state.projectDetailsList);
            return null;
        })
        .catch(err => console.log(JSON.stringify(err)));
};

setProjectDetailsList(projDetailsList){
    return (prevState) => {
        return {...prevState, projectDetailsList: projDetailsList};
    };
};

这些是日志:

>getProjectDetailsHelperEnd
>getProjectDetails Start:  
{status: 0, project_name: "Sample3", target: "Company1", creator: "agrawpri", timestamp: "2018-08-01 06:15:52", …}
>getProjDetails End: 
{3: {…}}
>getProjectDetails Start:  
{status: 1, project_name: "Sample2", target: "Company4", creator: "agrawpri", timestamp: "2018-08-01 05:57:11", …}
>getProjDetails End: 
{2: {…}, 3: {…}}

如您所见,getProjectDetailsListHelper()不需要等待地图完成,但是getProjectDetails方法可以正常工作。这是什么问题?

1 个答案:

答案 0 :(得分:0)

您需要使用Promise.all,然后从Promise回调中返回map

更改

getProjectDetailsListHelper(){
    return new Promise(async (resolve) => {
        await Object.keys(this.state.projectList).map(function (pid) {
            this.getProjectDetails(pid);
         }, this);
        console.log("getProjectDetailsHelperEnd");
    });
};

进入

async getProjectDetailsListHelper(){
    await Promise.all(Object.keys(this.state.projectList).map(function (pid) { // wait for all promises returned from map
        return this.getProjectDetails(pid); // return promise from getProjectDetails
    }, this));
    console.log("getProjectDetailsHelperEnd");
};