无法等待异步javascript代码

时间:2018-02-19 11:53:08

标签: javascript asynchronous


我目前正在创建一个简单的异步方法,但不知道某些内部异步逻辑是不是在等待
代码

this.getOwnerGroups = async function (creatorId) {
        let API = new Office365API(token, true);
        let result = "";
        let groups = []
        let memberOfs = await API.users.getMemberOfs(creatorId);

        //0 ==> OK
        debugger;
        await memberOfs.value.forEach(async group => {
            //1 ==> OK
            debugger;

            let owners = await API.groups.getOwners(group.id).then(owners => {
                //2 ==> NEVER REACHES THIS POINT
                debugger;
                owners.value.forEach(owner => {
                    if (owners.value && owners.value.length > 0) {
                        let isOwner = owners.value.some(user => (user.id === creatorId));
                        if (isOwner === true) {
                            //3 ==> After step 4 it enters at this point
                            debugger;
                            groups.push(group);
                        }
                    }
                });
            })
        });

        //4
        this.setState({ queriedGroups: groups }, () => { debugger; })
    }

此处遵循的步骤为:1,2,4,3 预期结果:1,2,3,4

1 个答案:

答案 0 :(得分:0)

您不应将.thenawait一起使用。您需要定义owners变量,如

let owners = await API.groups.getOwners(group.id);

之后以同步方式处理响应

owners.value.forEach(owner => ...)

您需要将.forEach替换为for..of。结果代码是

...
const groups = await memberOfs.value; 
for (let group of groups) {
  let owners = await API.groups.getOwners(group.id);
  owners.value.forEach(owner => ...)
}
...