在Promise实际解决之前运行下一行代码

时间:2018-12-06 14:57:54

标签: javascript

我试图重构所有嵌套为一个大函数的旧代码。在主要功能中,有几个返回数据的http调用和一个从本地存储读取的调用。

我试图回避的第一件事是从本地存储中读取内容,因为这引起了一些问题。我创建了一个单独的函数,并带有一个从localstorage读取的Promise,完成后将返回值(这是我的目的)。唯一的问题是我的应用程序不等待承诺解决。

我正在重构的庞大的整体派系:

 function activate() {
    HasAdminRole();
    getStates();


    datacontext.graph.getAboutMeBasic().then(function (dataUserDetails) {

        // If the user isn't a guest get the shared and personal routes.
        if (dataUserDetails.userType !== 'Guest') {
            vm.isUserGuest = false;
            getNavRoutesFromDb();
            getPersnonalDashboardSetting();
            getPersonalRoutesFromDb();
        }
        // If the user is a guest we only want to load the shared dashboards.
        else {

            vm.isUserGuest = true;

            // get all the groups a user is member of.
            datacontext.graph.getUserGroups().then(function (userGroups) {

                // get chosen navigation by the userSetting value.
                datacontext.usersetting.getUserSettingsByKey('Navigation').then(function (chosenNavigationName) {


                    console.log('de gekozen nav', chosenNavigationName)
                    // When a user is created the defautl navigation is "Algemeen", an external
                    // user is never allowed to see this navigation, thus it's save to say 
                    // that a user will be navigated to the external navigation
                    if (chosenNavigationName === 'Algemeen') {
                        chosenNavigationName = 'Klantenportaal';

                        console.log('before promise');


                        getUserData().then(function(userData) {
                            console.log('the user info', userData)

                            console.log('after promise');

                            console.log('the user: ', userInfo)

                            datacontext.settings.getSettingByName("Navigation").then(function(navigationId) {
                                console.log('nav id', navigationId);
                                datacontext.usersetting.updateUserSetting(userInfo.oneUserId, 11, 'Klantenportaal').then(function (userSettings) {
                                    console.log('user setting from update', userSettings)
                                });
                            })
                        })

                    }
                    console.log('nieuwe nav naam', chosenNavigationName);

                    try {
                        // get the allowedGroupId for the chosen navigation value.
                        datacontext.navigation.getNavigationByName(chosenNavigationName).then(function (result) {

                            // if the API returns error we redirect the user back to not authorized page.
                            if (result === 'error') {
                                window.location.href = '/Error/notauthorized';
                            }

                            var allowedGroupId = result.allowedGroupId;

                            if (allowedGroupId !== '') {
                                var isUserInGroup = 0;

                                // Loop over the groups a member is in. 
                                userGroups.map(function (group) {
                                    if (group.id === allowedGroupId) {
                                        isUserInGroup = 1
                                    }
                                });

                                //  If none of the groups match the allowedGroup, Log out the user.
                                if (isUserInGroup === 0) {

                                    window.location.href = '/Error/notauthorized';
                                }

                                // if the external group has no allowed group Id we log the user out. 
                                // We do this to prevent that all external users on a tenant can visit the customer portal.
                            } else {
                                window.location.href = '/Error/notauthorized';
                            }
                        })
                    } catch (e) {
                        window.location.href = '/Error/notauthorized';
                    }


                });
            });



            getPersnonalDashboardSetting();
            getExternalUserNavRoutes();
        }
    });

}

我要从本地存储读取的单独的promise函数

function getUserData() {
        console.log('reading promise');
        return new Promise((resolve, reject) => {
           var  userInfo = textservice.getUserInfoFromLocalStorage();
            resolve(userInfo);
        });
    }

enter image description here

如果在控制台中查看,我们可以看到诺言尚未解决,但代码仍在继续。如果有人能告诉我我在做什么错,我将不胜感激。

3 个答案:

答案 0 :(得分:2)

代码不会仅仅因为您调用了返回Promise的函数而被等待。

您还需要链接您的承诺。

在解决Promise之后需要运行的代码需要放入Promise链的下一个then()中。

看这个例子:

const getAsyncValue = (value) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(value)
    }, 300)
  })
}

getAsyncValue(1)
  .then(value => {
    // getAsyncValue(1) Promise has resolved,
    // value = 1
    return getAsyncValue(2)
  })
  .then(value => {
    // getAsyncValue(1) Promise has resolved,
    // value = 2

    // oops, forgot to return the following Promise.
    getAsyncValue(3)
    
    // getAsyncValue(3) Promise has NOT resolved yet.
  })
  .then(value => {
    // getAsyncValue(3) Promise is still NOT resolved,
    // value = undefined
    console.log('end')
    
    // At some point in the future, getAsyncValue(3) resolves, 
    // but it's too late.
  })

答案 1 :(得分:1)

您需要做的是await诺言。查看大段代码,调用函数getUserData()时,将其更改为:

await getUserData()

然后它将等待getUserData()方法执行完毕(承诺解决),然后再移至下一行代码。

答案 2 :(得分:-1)

我不确定,但是如果要下一个代码需要等待,可以将getUserData()放在前面。然后... 可能会起作用