This question already has answers here:
How do I convert an existing callback API to promises?
(24 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm currently refactoring some code, and I'm running into a problem.
I am trying to return the value from inside an anonymous function. I played around with it a few different ways, and tried await-ing it.
Essentially I'm getting data about the request that's being made, not the data from the request.
Here are some different ways I've tried working with it -
const run = async (text) => {
...
const s = personalityInsights.profile(req, (err, data) => {
...
return data; // correct value
});
return s; // incorrect value
};
const run = async (text) => {
...
personalityInsights.profile(req, (err, data) => {
...
return data;
});
};
const run = async (text) => {
...
return personalityInsights.profile(req, (err, data) => {
...
return data;
});
};
I can give the full code, but I think this is more of a language specific problem I have, than a code specific one.
Thanks for your help,
Ollie
Edit: This question has been marked as a duplicate, which I understand - but the solutions in that duplicate simply aren't working, and they aren't things I haven't already tried...
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 months ago.
This post was edited and submitted for review 10 months ago and failed to reopen the post:
Original close reason(s) were not resolved
How to get the output as a (global) variable from Promises in JavaScript? I found many answers but none helped me in applying to my problem. Specifically, I want to get the data from the code below. It is the node-os-utils library.
cpu.usage()
.then(info => {
console.log(info)
})
EDIT:
I tried to edit the code according to your recommendations, unfortunately I still couldn't find where I'm making a mistake.
I used the async function with await. Now I would like to return and display the value in systemdata, but the output shows Promise <pending>. I figured it's probably because the object is running in the stack before promise completes.
cpu.usage()
.then(cpuPercentage => {
return cpuPercentage +'%';
});
const printCpuUsage = async () => {
const a = await cpu.usage();
return a;
};
let systemdata = {
cpuCount: cpuCount,
cpuModel: cpuModel,
cpuUsage: printCpuUsage(),
// memoryUsage: ,
// CPUtemp: ,
// batteryCycle: ,
// StorageSize:
};
console.log(systemdata)
So I tried to put async directly into the object. With the assumption that this way the object property will have to wait for a promise.
const cpuusage = cpu.usage()
.then(cpuPercentage => {
return cpuPercentage +'%';
});
let systemdata = {
cpuCount: cpuCount,
cpuModel: cpuModel,
cpuUsage: async () => {
const a = await cpuusage;
return a;
},
// memoryUsage: ,
// CPUtemp: ,
// batteryCycle: ,
// StorageSize:
};
console.log(systemdata)
Unfortunately this code output: cpuUsage: [AsyncFunction: cpuUsage]
try this:
// global scope
let globalInfo;
cpu.usage().then(info => {
globalInfo = info;
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return values from async functions using async-await from function? [duplicate]
(3 answers)
Closed 3 years ago.
I'm trying to load a CSV file into my application at the beginning and keep the value in a variable and call it from other functions instead of accessing by then all the time
my code is
var DVizModule = (() => {
let dataset = [];
let _data = async () => {
const data = await d3.csv("data/alphabet.csv");
return data;
}
let data = _data().then(data => {
dataset = data;
return dataset;
})
return {
data: data
}
})();
console.log(DVizModule.data);
it returns
Promise pending proto: Promise
PromiseStatus: "resolved"
PromiseValue: Array(26)
When I write
const t = async function() {
const data = await d3.csv("data/alphabet.csv");
return data;
}
t().then(result => console.log(result))
it returns the file perfectly
I'm trying to access the file content via
DVizModule.data
If you want to access data synchronously, you should declare it as a plain value, not a promise. something like this should do the trick:
const DVizModule = {};
d3.csv("data/alphabet.csv").then(data => DVizModule.data = data);
Note, of course, that DVizModule.data will be undefined until the request is actually complete. If you want to ensure that the value actually is there, you will have to wrap the outer context into an async function and await the data at the very beginning. This way you can both ensure that the value is present when you code accesses it and use it in a synchronous manner.
Hope I got your question right and not trying to resolve the wrong problem ;)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a very simple function here trying to grab a post from r/askreddit.
const simple_get = require('simple-get');
function get_post() {
simple_get('https://reddit.com/r/askreddit/random.json', (err, res) => {
if (err) {
console.log(err);
}
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
var post = JSON.parse(JSON.stringify(eval('(' + body + ')')))
console.log(post);
return post;
});
});
}
console.log(get_post());
The function returns undefined. However, when post is outputted on line 17 (inside the function), it returns the correct object. Here are some logs:
undefined.....reddit.js:23
Array(2) [Object, Object].....reddit.js:17
Alongside simply returning post, I have tried making a global variable and setting that to post. That also didn't work. I need it as a function so I can set it in a while loop to do things like get a new post if it's a mod post, so alternatives to that would also be appreciated.
Node version 10.15.0 with simple-get 3.1.0 on MacOS Mojave 10.14.6.
Thanks for the help :)
simple_get is an async function, it means your code goes through console.log() before it actually receives any response
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to make a function wait until a callback has been called using node.js
(11 answers)
Closed 5 years ago.
I'm learning node.js and I have a problem. How to get data from function to variable?
function loadOrInitializeTaskArray(file, cb) {
fs.exists(file, function(exists) {
var tasks = [];
if (exists) {
fs.readFile(file, 'utf8', function(err, data) {
if (err) throw err;
var data = data.toString();
var tasks = JSON.parse(data || '[]');
cb(tasks);
})
} else {
cb([]);
}
})
}
function listTasks(file) {
loadOrInitializeTaskArray(file, function(tasks) {
for (var i in tasks) {
console.log(tasks[i]);
}
})
}
Function listTasks works correctly, but I would like create own function, for example customListTasks:
function customListTasks(file) {
var list = loadOrInitializeTaskArray(file, function(){});
console.log(list);
}
This not return me errors, but console.log on list return me "undefined". How can I get this data to variable list?
Short answer: you can not.
Because the loading in loadOrInitializeTaskArray is asynchronous, all the magic has to happen in the callback that you are passing. You cannot just 'return' a value from it.
Option 1: Place all logic that depends on the loaded data in the anonymous function that you pass as callback.
var list = loadOrInitializeTaskArray(file, function(tasks){
console.log(tasks);
});
Option 2: Use Promises. They work essentially like callbacks, but are slightly more flexible and make chaining easier.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a function that creates an object based on db data, and some web_based json.
function makeObject(dbdata){
var obj = {};
obj.id = dbdata.id;
obj.url = dbdata.url;
request(dbdata.url,function(err,res,body){
obj.inventory = JSON.parse(body).inventory;
});
return obj
}
This obviously doesn't fill in the inventory property (async, etc...) nor does it work with the return inside request. I know the answer is pretty basic, but I just can't see it. help,please!
You can either pass in a callback argument or return a promise. request has to return a promise or you have to promisify it in some way. The callback solution is easier to get going as it stands.
function makeObject(dbdata, cb) {
/* your codes */
request(args, function (err, res, body) {
obj.inventory = JSON.parse(body).inventory;
cb(err, obj);
});
}
Then you would use it like so
makeObject(dbdata, function (err, obj) {
// handle err
// do things with obj
});