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);
函数子类型由intentMap调用, 在它里面,harry 函数返回一个 promise ,一旦 promise 得到解决,我将从 firebase 获取数据并希望使用 agent.add 显示它 在 console.log 中获取预期输出,但 agent.add 为空 而agent.add正在issuetype函数中工作
最佳答案
问题的一部分是你混合了 Promise 和回调,有时返回 Promise,有时不返回。如果您牢记一些准则,这是最简单的:
- 确保返回 Promise。
- 确保对
agent.add()
的调用位于.then()
子句内。 - 如果您使用回调函数,则在大多数情况下可以将其切换为使用 Promises。
请记住,您不需要将其包装到新的 Promise 中,因为如果您不为其提供回调函数,Firebase 调用就会返回一个 Promise。
例如,您的线路
admin.database().ref('Support/issuesubtype/'+res).once('value', function(snap) {
最好重写为
return admin.database().ref('Support/issuesubtype/'+res).once('value')
.then( snap => {
这里的重点是您要返回 Promise,并且使用 Promise 而不是回调来处理该函数。
关于javascript - agent.add 在 Promise.then 对话框流中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63685026/