如何解决agent.add在promise.then内部不起作用
function issuetype(agent) {
//let i = 0;
console.log('inside issuetype');
return admin.database().ref('Support/issuetype').once('value',function(snapshot) {
var data = snapshot.val();
var array = Object.values(data);
console.log('Issues are');
console.log(array);
agent.add(`Select your issue `); //works fine
for(const val of array){
agent.add(new Suggestion(`${val}`));
}
console.log(data);
});
}
function subtype(agent) {
let data;
let value;
let id;
console.log('inside subtype');
let harry = new Promise(function(resolve,reject){
admin.database().ref('Support/issuetype').once('value',function(snapshot) {
value = agent.parameters.sub;
console.log('inside promise');
data = snapshot.val();
console.log('Key'+Object.keys(data));
console.log('Value'+value);
id = Object.keys(data).find(key => data[key] === value);
console.log('Matched id');
console.log(id);
if(id){
resolve(id);strong text
}else{
reject('not resolved');
}
});
});
harry.then(function(res){
console.log('Type of id:'+typeof(res));
console.log('id is:'+res);
agent.add(`Select your sub issue ret`);
admin.database().ref('Support/issuesubtype/'+res).once('value',function(snap) {
var snapdata = snap.val();
var values = Object.values(snapdata);
console.log(typeof(values));
console.log('SubIssues are'); // displayed in console
console.log(values);
agent.add(`Select your sub issue `); // not displayed
return agent.add(`Select your sub issue `); // not displayed
for(const k of values){
agent.add(new Suggestion(`${k}`)); // not displayed
}
});
}).catch(function(rej){
console.log(rej);**strong text**
}).then(function(rej){
console.log('Irrespctive');
});
}
intentMap.set('issuetype',issuetype);
intentMap.set('subtype',subtype);
Function子类型由intentMap调用, 在其内部,harry函数返回一个promise,一旦promise被解决,我就从firebase获取数据,并希望使用agent.add显示它 在console.log中获得预期的输出,但是agent.add为空 而agent.add在问题类型功能中起作用
解决方法
部分问题是您混合了Promises和回调,有时返回Promise,有时不返回。牢记一些准则是最简单的:
- 确保您退还承诺。
- 确保对
teacher_year = request.POST.get('teacher_year') # if request.POST doesn't contain teacher_year it returns None if teacher_year: ...
的调用在agent.add()
子句内。 - 如果您使用的是回调函数,则在大多数情况下可以将其切换为使用Promises。
请记住,您不需要将其包装到新的Promise中,因为Firebase调用会在您不提供回调函数的情况下返回Promise。
例如,您的行
.then()
最好改写为
admin.database().ref('Support/issuesubtype/'+res).once('value',function(snap) {
这里重要的一点是,您将返回Promise,并且使用Promise而不是回调来处理该函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。