I don't think this is duplicate question since this does not concern jquery.
I am trying to build a chatbot that returns artist info when queried by our user. I am using Promise to wait for DB accessing then process the result to send back to user. However, the code continues regardless of our promise object.
We get the input from a user which then WATSON categorize it as a 'ask' type conversation. Then, we use the Promise object to access the DB and store the data from there and print it back to the user. Any thoughts on how to make our code actually stop until finish accessing the DB?
let getConversationResponse = (message, context) => {
console.log("getConversationResponse in")
let payload = {
workspace_id: process.env.WORKSPACE_ID,
context: context || {},
input: message || {}
};
console.log("getConversationResponse : declare")
payload = preProcess(payload);
console.log("getConversationResponse : return promise")
return new Promise((resolved, rejected) => {
// Send the input to the conversation service
conversation.message(payload, function(err, data) {
if (err) {
rejected(err);
}
else {
console.log("Check"+data.context.type);
if(data.context.type == 'ask'){
let artist = "Jan Tarasin";
var iniPromise = artpromise(artist);
iniPromise.then(function(result) {
console.log(result);
console.log(data.output.text);
});
}
let processed = postProcess(data);
///////////////////////////////////////////////////
///////////////////////////////////////////////////
console.log("getConversationResponse : return promise : postProcess done");
if (processed) {
// if return value is the promise object,
if (typeof processed.then === 'function') {
processed.then(data => {
resolved(data);
}).catch(err => {
rejected(err);
})
}
// if return value is the changed data
else {
resolved(processed);
}
}
else {
// if there is no return data
resolved(data);
}
}
});
})
}
The artpromise function is below:
function artpromise (artist) {
return new Promise(function(resolve, reject) {
const MongoClient = require("mongodb").MongoClient;
const url = 'mongodb://localhost:27017/mydb';
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var query = {name: artist};
artistinfo = dbo.collection("artistdb").find(query)
.toArray(function(err, result) {
if (err) throw reject(err);
resolve(result);
});
db.close();
})
});
};