Javascript 下一行代码在Promise实际解析之前运行
我试图重构一段旧代码,它全部嵌套为一个大函数。在主函数中,有几个返回数据的http调用和一个从本地存储读取数据的调用 我尝试重构的第一件事是读取本地存储,因为这会导致一些问题。我创建了一个单独的函数,它承诺从localstorage读取数据,完成后将返回值(至少这是我的目的)。唯一的问题是我的应用程序没有等待承诺的解决 我正在重构的庞大集团:Javascript 下一行代码在Promise实际解析之前运行,javascript,Javascript,我试图重构一段旧代码,它全部嵌套为一个大函数。在主函数中,有几个返回数据的http调用和一个从本地存储读取数据的调用 我尝试重构的第一件事是读取本地存储,因为这会导致一些问题。我创建了一个单独的函数,它承诺从localstorage读取数据,完成后将返回值(至少这是我的目的)。唯一的问题是我的应用程序没有等待承诺的解决 我正在重构的庞大集团: function activate() { HasAdminRole(); getStates(); datacontext
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();
}
});
}
我的单独承诺函数从localstorage读取
function getUserData() {
console.log('reading promise');
return new Promise((resolve, reject) => {
var userInfo = textservice.getUserInfoFromLocalStorage();
resolve(userInfo);
});
}
如果我们查看控制台,我们可以看到承诺尚未解决,但代码仍在继续。如果有人能告诉我我做错了什么,我将不胜感激。代码不会因为您调用了返回承诺的函数而等待 你还需要把你的承诺串起来 在
Promise
解决后需要运行的代码需要放在Promise链的下一个then()
中
看看这个例子:
const getAsyncValue=(值)=>{
返回新承诺(解决=>{
设置超时(()=>{
解析(值)
}, 300)
})
}
getAsyncValue(1)
.然后(值=>{
//getAsyncValue(1)承诺已解决,
//值=1
返回getAsyncValue(2)
})
.然后(值=>{
//getAsyncValue(1)承诺已解决,
//值=2
//哎呀,忘了还下面的承诺。
getAsyncValue(3)
//getAsyncValue(3)承诺尚未解决。
})
.然后(值=>{
//getAsyncValue(3)承诺仍未解决,
//值=未定义
console.log('end')
//在将来的某个时候,getAsyncValue(3)解析,
//但是太晚了。
})
代码不会因为调用了返回承诺的函数而等待
你还需要把你的承诺串起来
在Promise
解决后需要运行的代码需要放在Promise链的下一个then()
中
看看这个例子:
const getAsyncValue=(值)=>{
返回新承诺(解决=>{
设置超时(()=>{
解析(值)
}, 300)
})
}
getAsyncValue(1)
.然后(值=>{
//getAsyncValue(1)承诺已解决,
//值=1
返回getAsyncValue(2)
})
.然后(值=>{
//getAsyncValue(1)承诺已解决,
//值=2
//哎呀,忘了还下面的承诺。
getAsyncValue(3)
//getAsyncValue(3)承诺尚未解决。
})
.然后(值=>{
//getAsyncValue(3)承诺仍未解决,
//值=未定义
console.log('end')
//在将来的某个时候,getAsyncValue(3)解析,
//但是太晚了。
})
你需要做的是等待承诺。在调用函数getUserData()
时,查看大量代码,将其更改为:
await getUserData()
然后,它将等待
getUserData()
方法完成执行(promise to resolve),然后再转到下一行代码。您需要做的是等待承诺。在调用函数getUserData()
时,查看大量代码,将其更改为:
await getUserData()
然后,它将等待getUserData()
方法完成执行(承诺解析),然后再转到下一行代码。我不确定,但如果您想等待下一个需要等待的代码,可以放在前面等待getUserData()。然后。。。
可能它会起作用我不确定,但是如果你想下一个需要等待的代码,你可以把它放在前面等待getUserData()。然后。。。
它可能会起作用getUserInfoFromLocalStorage做什么呢
我认为在阅读了一些有关javascript异步行为的主题后,您会对您的问题有更好的理解。您可以从这里开始:getUserInfoFromLocalStorage
做什么?我认为在阅读了一些关于javascript异步行为的主题之后,您会对您的问题有更好的理解。你可以从这里开始:我想说,大多数代码都需要重新编写,要么使用链式承诺,要么使用async/await
,但至少在这么大的一块代码中,不能两者都使用。我建议使用async/await
语法,因为链式承诺可能会变得非常混乱。我想说,大多数代码都需要重新编写,要么使用链式承诺,或者async/await
,但不能两者兼而有之,至少在这一大块中是这样。我建议使用async/await
语法,因为链接承诺可能会变得非常混乱。