This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
I have a module.exports with multiple functions inside.
What I have understod, it is possible to share a variable to another file.
But I cannot seem to get it work.
translator.js
module.exports = {
translatorfunc: function (message, queryInput, callback) {
var parameters = {
text: queryInput
};
var parameters = {
text: queryInput,
model_id: 'es-en'
};
languageTranslator.translate(
parameters,
function (error, response) {
if (error)
bot.reply(message, 'Cannot find language that should understand this.')//console.log(error)
else
var TranslatedOutput = response.translations[0].translation;
assistant.message({
input: { 'text': TranslatedOutput }
}, function (err, response) {
if (err)
console.log('error:', err);
else
queryOutput = response.output.text[0];
var parameters = {
text: queryOutput,
model_id: 'en-es'
};
languageTranslator.translate(
parameters,
function (error, response) {
if (error)
bot.reply(message, 'Cannot find language that should understand this.')//console.log(error)
else
TranslatedOutput = response.translations[0].translation;
}
)
});
}
)
}
}
The variable I'm trying to send to a different file is TranslatedOutput
I also tried to wrap the function languageTranslator.translate as a function, but when I'm calling the variable, it says undefined.
And to get the variable
var translator = require('./tools/translator')
console.log(translator.translatorfunc.TranslatedOutput);
You have to make your variable an attribute of the module.exports object:
module.exports.TranslatedOutput = 'something';
This way you can import it like that:
var TranslatedOutput = require('myModule'). TranslatedOutput;
Related
This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 1 year ago.
I have checked some links to compare two array but
I want to compare and check if the value which are present in database are similar to value which are present in fileName
Problem is fileName is not and Array and I am passing Value to it via For Each from another function so it can be any value
fileName= JavaScript
fileName= Java
fileName= NodeJs
fileName= ReactJs
fileName= Oops
but singleProduct is array that's why I used for loop to extract name from it.
code:
function checkDoc(data, childProduct, fileName, pathName, req, res) {
return new Promise((resolve, reject) => {
Document.findAll({
raw: true,
where: {
product_id: childProduct.id,
},
})
.then((productDoc) => {
productDoc.forEach((singleProduct) => {
if (singleProduct.name === fileName) {
//print matched value
} else {
//print unmatched value
}
});
})
.catch(function (err) {
return reject(
getFailureResponseJson("Can't be added please try again :) " + err)
);
});
});
}
value present inside singleProduct.name
Oops
Java
JavaScript
value present inside fileName
Oops
Java
JavaScript
NodeJs
ReactJs
Need Output like this
Matched Value:
Oops
Java
JavaScript
Unmatched Value:
NodeJs
ReactJs
You can try storing the values on to 2 arrays.
...
const matchedValues = [];
const unmatchedValues = [];
if (singleProduct.name === fileName) {
matchedValues.push(fileName)
} else {
unmatchedValues.push(fileName)
}
...
// Print
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
I am trying to get one of the events outside and print it. Of course the 'answer' variable scope is only inside.
As you can see, this one gets a list of all the events stored on a specific calendar. I am able to access specific events from the array. However. I don't know how to get that one value out of this.
I am not that familiar with coding, help appreciated.
//my question is just above the last line.
let google = require('googleapis');
let privatekey = mypk.json;
// configure a JWT auth client
let jwtClient = new google.auth.JWT(
privatekey.client_email,
null,
privatekey.private_key,
['https://www.googleapis.com/auth/calendar']);
//authenticate request
jwtClient.authorize(function (err, tokens) {
if (err) {
console.log(err);
return;
} else {
console.log("Successfully connected!");
}
});
let calendar = google.calendar('v3');
calendar.events.list({
auth: jwtClient,
calendarId: 'xxxxx#group.calendar.google.com'
}
, function (err, response, cb) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var events = response.items;
var singleEvent = events[0].summary;
return;
/* if (events.length == 0) {
console.log('No events found.');
} else {
console.log('Event from Google Calendar:');
for (let event of response.items) {
console.log('Event name: %s, Creator name: %s, Create date: %s', event.summary, event.creator.displayName, event.start.date);
}
}*/
}
);
//this is what I need to get, one event but the variable has no scope here.
console.log ('this is the ' + singleEvent);
Declare the variable singleEvent just after calendar
Like this:
let calendar = google.calendar('v3');
let singleEvent;
And inside the callback do the following:
singleEvent = events[0].summary;
Note: Understanding scopes in Javascript is probably the most important thing you need to learn. This article will probably help you a lot:
https://scotch.io/tutorials/understanding-scope-in-javascript
This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 5 years ago.
I'm new in JS and async... so I need help :)
I need to return value after serial communication. reading serial apparently need to be function, so I dont know how to make it blocking, or return value from it... console log shows value, but value is not returned...(probably because its executed before serial). please help. Here is part of code:
var LightController = {
getBrightness: function() { //get brightness
port.write(askcommand);
port.on('data', function (data) {
st = data.slice(-4, -3);
this.brightness = st.readInt8(0);
console.log(this.brightness)
});
return this.brightness;
},
lightAccessory
.getService(Service.Lightbulb)
.addCharacteristic(Characteristic.Brightness)
.on('get', function(callback) {
callback(null, LightController.getBrightness());
});
var LightController = {
// add callback to get brightness function
getBrightness: function(brightnessCallback) { //get brightness
port.write(askcommand);
port.on('data', function (data) {
st = data.slice(-4, -3);
this.brightness = st.readInt8(0);
console.log(this.brightness)
// call callback for get brightness function
brightnessCallback(this.brightness);
});
return this.brightness;
}
}
lightAccessory
.getService(Service.Lightbulb)
.addCharacteristic(Characteristic.Brightness)
.on('get', function(callback) {
// call the get brightness function, passing anonymous function as brightness callback
LightController.getBrightness(function(brightness){
// call original callback with brightness
callback(null, brightness);
})
});
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I have a schema which saves Cat information. I then want to create an array of all the cat_urls, however when I call the array outside of the dbs call, the array is empty
var cat_urls = [];
Cat.find(function (err, data) {
var stringify = JSON.stringify(data)
content = JSON.parse(stringify);
content.forEach(function (result) {
cat_urls.push(result.cat_url);
})
console.log(cat_urls, 'here')
})
console.log(cat_urls, 'here not working') // I want cat_urls to also be populated here
So Inside the Cat.find() call cat_urls has values like this:
[ 'www.hello.co.uk', 'www.testing.co.uk' ] 'here'
But outside cat_urls = []
I guess this is to do with the fact that node js does not run in a specific order, but how can I solve this issue?
I think it's working but your find function returns a promise that resolves asynchronously.
Try:
var cat_urls = [];
Cat.find(function (err, data) {
var stringify = JSON.stringify(data)
content = JSON.parse(stringify);
content.forEach(function (result) {
cat_urls.push(result.cat_url);
})
console.log(cat_urls, 'here')
}).then(function(){
// Promise has completed, now this console log will trigger only after the cat's names are pushed.
console.log(cat_urls);
})
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I'm having some scope issues when trying to save my return data to a parent scope. Here is my source, any help would be greatly appreciated. I can not for the life of me get table to = data.
My data var console.logs correctly its just a problem of scope.
function OpenDB(mongoUrl, callBack){
var MongoClient = mongodb.MongoClient;
var url = mongoUrl || "mongodb://" + process.env.IP + "/test";
MongoClient.connect(url, function(err, db) {
if(err){
console.log(err);
}
console.log(" Connected correctly to server ");
callBack(db, function(){
console.log(" Disconnected from server ");
db.close();
});
}.bind(this));
}
var GetTableAsArray = function(tableName){
var table = [];
OpenDB(null, function(db,cb){
db.collection(tableName).find().toArray(function(err, data){
if(err){
console.log(err);
}
//this is the problem
table = data;
cb();
});
});
return table;
};
By the time GetTablesAsArray function returns, table is still just an empty array. The problem here is that your query happens in an asynchronous way, meaning that you're code doesn't wait for it to be done before proceeding. You can use a callback to execute whatever code you want with the value of tables once it is fetched.
var GetTableAsArray = function(tableName, callback){
OpenDB(null, function(db,cb){
db.collection(tableName).find().toArray(function(err, data){
if(err){
console.log(err);
}
//this is the problem
table = data;
cb();
callback (data);
});
});
};
GetTableAsArray('tableName', function (table) {
console.log(table);
});