I am using npm memcached package https://www.npmjs.com/package/memcached
It is possible to return data from memcached get method?
Now return data is undefined/
memcached.set('foo', 'bar', 10, function (err) { });
let data1;
memcached.get('foo', function (err, data) {
console.log(data); // bar
data1 = data
});
console.log(data1); // undefined
let data2 = memcached.get('foo', function (err, data) {
console.log(data); // undefined
return data;
});
console.log(data2); // undefined
let data3 = async () => {
let result = await memcached.get('foo', function (err, data) {
console.log(data); // bar
});
console.log(result); // undefined
return result;
}
console.log(data); // {}
You can't return from get() as it's an asynchronous callback. What you can do is:
with callbacks:
memcached.get('foo',(err, data) => {
if(err) {
console.log('error: ', err);
} else {
console.log('data: ', data);
}
});
with promises:
memcached.get('foo')
.then((data) => {
console.log('data: ', data);
})
.catch((err) => {
console.log('error: ', err);
});
and with async/await:
const getData = async () => {
try {
const data = await memcached.get('foo');
console.log('data: ', data);
} catch (err) {
console.log('error: ', err);
}
}
hope this helps :)
Since memcached is async you can't really return from it, altho I see OP found a way via a promisify wrapper. What you can do is call another function from inside the callback.
Working with async socket communication I've had to split up a lot of my workflows into request and receives.
memcached.get('foo',(err, data) => {
doStuff(data);
});
function doStuff(data) {
//do some stuff here
}
Of course you could always do your work with the data inside the handler too. But in some cases that isnt the best approach.
Related
I'm getting github repo data, and then i store it in redis with set. with get am getting current data, but when i trying add function to get it's not working.
let redisClient;
(async () => {
redisClient = redis.createClient();
redisClient.on("error", (error) => console.error(`Error : ${error}`));
redisClient.on("connect", function () {
console.log("Redis Connected!");
});
await redisClient.connect();
})();
// Make request to Github for data
async function getRepos(req, res, next) {
try {
console.log("Fetching Data...");
const { username } = req.params;
// with this am getting result
const cacheResults = await redisClient.get(username);
console.log(cacheResults);
// with this am not getting result, how can i fix this?
redisClient.get(username, (err, data) => {
console.log(data);
});
const response = await fetch(`https://api.github.com/users/${username}`);
const data = await response.json();
const repos = data.public_repos;
// Set data to Redis
redisClient.set(username, JSON.stringify(repos));
res.send(setResponse(username, repos));
} catch (e) {
console.log(e);
res.status(500);
}
}
it's don't console.log(data), i searched a lot and everyone have one example how to use get function, but in me case it's don't log, whats am doing wrong?
this is my cache function
// Cache middleware
async function cache(req, res, next) {
const { username } = req.params;
try {
await redisClient.get(username).then((data) => {
if (data !== null) {
res.send(setResponse(username, data));
} else {
next();
}
});
} catch (error) {
console.log(error.toString());
}
}
app.get("/repos/:username", cache, getRepos);
it's works, but time finish times with cache and without it are same? am doing something wrong?
can you try like this
redisClient.get(username).then((data) => {
console.log(data);
});
var promise = require('child-process-promise').spawn;
promise('some_command_producing_output')
.then(function (result) {
...
})
.catch(function (err) {
...
});
What I want is to add some processing after command produced output in stdout. So finally I want to create a function to use like this:
RunCommandAndProcess('some_command_producing_output')
.then(function (result) {
...
})
.catch(function (err) {
...
});
The function should use promise from child-process-promise, wait until successful result produced and return promise for processing data.
Welcome to Stack Overflow #ScHoolboy.
I cansuggest you use a basic child-process module from Node.js and promising it yourself in the following way
const spawn = require('child_process').spawn;
const spawnPromise = (cmd, args) => {
return new Promise((resolve, reject) => {
try {
const runCommand = spawn(cmd, args);
runCommand.stdout.on('data', data => resolve(data.toString()));
runCommand.on('error', err => {
throw new Error(err.message);
});
} catch (e) {
reject(e);
}
});
};
Where:
cmd - command, for example, "echo"
args: array of arguments, for example ["Hello world"]
You can call the function as RunCommandAndProcess if you need :)
Example of usage:
spawnPromise('ls', ['-la']).then(data => console.log('data: ', data));
Or
const result = await spawnPromise('ls', ['-la']);
You can do it by
var spawn = require('child-process-promise').spawn;
var promise = spawn('echo', ['hello']);
var childProcess = promise.childProcess;
console.log('[spawn] childProcess.pid: ', childProcess.pid);
childProcess.stdout.on('data', function (data) {
console.log('[spawn] stdout: ', data.toString());
});
childProcess.stderr.on('data', function (data) {
console.log('[spawn] stderr: ', data.toString());
});
promise.then(function () {
console.log('[spawn] done!');
})
.catch(function (err) {
console.error('[spawn] ERROR: ', err);
});
For the more information please check the documentation
I'm performing an API call to Bing Web Search API and running into an error with the response.
Here's the code:
await webSearchApiClient.web.search(searchText).then(result => {
console.log('Results API', result)
return result
}).catch((err) => {
throw err;
})
The issue I'm running into is that the result does come back (the console log 'Results API' prints the expected return values), but the return statement isn't passing the value along. The rest of the code is written to be asynchronous, and when I print the values in the code calling the API function I get this:
Line 1: Results API {"_type": "SearchResponse","queryContext": {"originalQuery":...
Line 2: Returned Results undefined
I've tried setting the result to other variables with no success
I'm using redux as well, here's the code for the dispatch call and the code in the redux action (the second console log is the the redux actions):
const onSearchResults = async () => {
dispatch(getWebResults(searchText))
dispatch(getImageResults(searchText))
}
export const getWebResults = (searchText) => {
return async dispatch => {
const onStart = () => {
dispatch({ type: GET_WEB_RESULTS_STARTED });
}
const onSuccess = (response) => {
dispatch({ type: GET_WEB_RESULTS_SUCCESS, payload: response });
return response;
}
const onError = (error) => {
dispatch({ type: GET_WEB_RESULTS_FAILURE, payload: error });
return error;
}
try {
onStart();
const webResults = await BingWebSearchApi(searchText);
console.log('Returned Results', webResults)
return onSuccess(webResults)
} catch(error) {
return onError(error)
}
}
}
Instead of doing this
await webSearchApiClient.web.search(searchText).then(result => {
console.log('Results API', result)
return result
}).catch((err) => {
throw err;
})
Since the return statement is for the then function scope, you should return the promise like this
return webSearchApiClient.web.search(searchText);
And then in your redux actions do something like
(...)
try {
onStart();
BingWebSearchApi(searchText).then((webResults)=> {
console.log('Returned Results', webResults);
onSuccess(webResults);
});
} catch(error) {
return onError(error)
}
I have an application running on NodeJS(express + mongoose + jade).
I have a post-route /search (all routes are in a separate module) which should handle fetching data from mongo database and inserting it into jade template(in this case just printing th console):
router.post('/search', function (req,res) {
var componentsArray = null;
function getArray(){
console.log('Initializing...');
componentsArray = dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
}
getArray(function () {
console.log('Documents returned.');
console.log('Printing array...');
console.log('Array: ' + componentsArray);
console.log('Array type: ' + typeof (componentsArray));
console.log('Rendering page...');
res.render('search_results');
});
});
Searching and fetching function implemented in a different module dataExchanger:
exports.search = function(select, type, data) {
console.log('Fetching documents...');
componentsModel.find({name: data}, function (err, docs) {
if(!err) {
console.log('Returning documents...');
return docs;
} else {
console.log('Can\'t return documents!');
throw err;
}
});
};
The problem is that when I am using a callback function for getArray(), the server just freezes at the moment of returning docs and stops responding.
What am I doing wrong?
Try to use async/await
router.post('/search', async (req,res) => {
let componentsArray;
try {
componentsArray = await dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
} catch(e){
//If error in request and no data.
console.error('Error', e.message);
return res.render('error_message');
}
console.log('Documents returned.');
console.log('Printing array...');
console.log('Array: ' + componentsArray);
console.log('Array type: ' + typeof (componentsArray));
console.log('Rendering page...');
res.render('search_results');
});
And here is your dataExchanger
exports.search = function(select, type, data) {
console.log('Fetching documents...');
return new Promise((resolve, reject) => {
componentsModel.find({name: data}, function (err, docs) {
if(err) return reject(err);
resolve(docs);
});
})
};
Further reading: promises, async/await
router.post('/search', function (req,res) {
var componentsArray = null;
function getArray(cb){
console.log('Initializing...');
componentsArray = dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
//Execute the callback
cb();
}
getArray(function () {
console.log('Documents returned.');
console.log('Printing array...');
console.log('Array: ' + componentsArray);
console.log('Array type: ' + typeof (componentsArray));
console.log('Rendering page...');
res.render('search_results');
});
});
Looks like your search method is async as well, so you will need to pass the callback down to that to get the desired result.
I am using ldapjs library in nodejs. I want to access the results of client.search outside of the function.
Here is my code
items = [];
client.search('cn=users,dc=test,dc=com', opts, function (err, res) {
if (err)
console.log(err);
res.on('searchEntry', function (entry) {
items.push(entry.object);
});
res.on('error', function (err) {
console.error('error: ' + err.message);
});
res.on('end', function (result) {
console.log('status: ' + result.status);
console.log(items[0]); **//Prints results correctly**
});
});
console.log(items[0]); **//Prints []**
I tried return items inside search. Still doesn't print. Any suggestions?
I encountered the same problem. Since res.on 'searchEntry' is an event emitter
, a simple solution that I use is to wrap the whole thing in a promise and return that.
let search = function( 'cn=users,dc=test,dc=com', opts ) {
return new Promise( ( resolve, reject ) => {
items = [];
client.search('cn=users,dc=test,dc=com', opts, function (err, res) {
if (err)
console.log(err);
reject( err )
res.on('searchEntry', function (entry) {
items.push(entry.object);
});
res.on('error', function (err) {
console.error('error: ' + err.message);
reject( error )
});
res.on('end', function (result) {
console.log('status: ' + result.status);
console.log(items[0]); **//Prints results correctly**
resolve( items )
});
});
}
};
Then you can do something like this:
let entries = await search( 'cn=users,dc=test,dc=com', opts );
You can use a wrapper function and a callback
function search(dn, options, callback){
// your code ...
res.on('end', function (result) {
callback(items);
}
});
and to call it like this
search(dn, options, function(err, result) {
//your result ...
console.log(result);
}