为什么我无法访问一个"then"块中的父范围变量,但我在后续块中具有访问权限?



我正在为一个开源的Ember应用程序做出贡献,我正在尝试将几个承诺链接在一起。 以下代码的目的是将用户设置到 PouchDB 存储的current_user文档中,然后将他们的 i18n 首选项设置到preferences存储中。 代码如下:

setCurrentUser(userName) {                                 // block 0
let config = this.get('configDB');
let sessionData = this.get('sessionData');
if (!userName && sessionData.authenticated) {
userName = sessionData.authenticated.name;
}
config.get('current_user').then((doc) => {               // block 1
doc.value = userName;
config.put(doc);
return userName;
}).then((user) => {                                      // block 2
let configDB = this.get('configDB');
let preferences = configDB.get('preferences');
let promises = { user, preferences };
return RSVP.hash(promises);
}).then((promises) => {                                 //  block 3
let { preferences } = promises;
let userName = promises.user.name || 'default';
this.set('i18n.locale', preferences[userName].i18n);
}).catch((err) => {                                      // block 4
console.log(err);
config.put({_id: 'current_user', value: userName});
});
}

如您所见,userName变量作为参数传递给setCurrentUser方法。 因此,我希望在每个then块中的每个代码块中访问此参数。

然而,事实并非如此。 我确实可以在块 0、1、3 中访问它,甚至在块 4 的catch范围内。 但是由于某种原因,我无法访问块 2 中的它。 上面的代码,特别是传递带有首选项文档和用户对象的 RSVP 对象,代表了使我的代码正常工作的黑客解决方法。 但是,我更喜欢做这样的事情:

setCurrentUser(userName) {                                 // block 0
let config = this.get('configDB');
let sessionData = this.get('sessionData');
if (!userName && sessionData.authenticated) {
userName = sessionData.authenticated.name;
}
config.get('current_user').then((doc) => {               // block 1
doc.value = userName;
config.put(doc);
return userName;
}).then((user) => {                                      // block 2
let configDB = this.get('configDB');
let preferences = configDB.get('preferences');
return preferences[userName].i18n || preferences['default'].i18n;
}).then((i18nPreference) => {                            // block 3
this.set('i18n.locale', i18nPreference);
}).catch((err) => {                                      // block 4
console.log(err);
config.put({_id: 'current_user', value: userName});
});
}

事实上,我已经尝试了上述方法,但我在块 2 内Uncaught ReferenceError: userName is not defined,因此被路由到catch块。

我的问题是,块 0/1/3/4 和块 2 之间有什么区别,它们允许第一个块访问userName但会阻止块 2 这样做?

据我所知,用户名在您的代码中没有大写的 N(所以它是一个不同的变量(:

}).then((user) => {
let configDB = this.get('configDB');
let preferences = configDB.get('preferences');
return preferences[username] || preferences['default'];

您说此代码仅用于说明目的。最好知道返回错误消息的实际代码是什么,以便有更好的主意。

最新更新