Reputation:
Please be advised that this topics is not trivial for beginners, even reading older posts.
So I wrote a small Node.Js application where a function in the main application calls another function on a custom module. This function uses a callback, but I need a callback to the callback.
Here's what I'm trying to do:
// file sample.js
function foo(param, callback) {
request.get({
url: <url>
headers: {<headers>}
}, (err, response, data) => {
array = []
obj.forEach(function (entry) {
// do stuff with array
};
});
callback(null, array);
});
}
module.exports.foobar = foo;
Then on my app.js
file, I'm calling function foo
multiple times like this:
// file app.js
function bar(err, data) {
//do things with data
}
}
var param = 'some param';
foo(param, bar);
param = 'some other param';
foo(param, bar);
but i want to use data
(a json
obj) outside the bar
function, like assign it to different variables. Do I make another callback inside bar
?
Upvotes: 0
Views: 43
Reputation: 828
You should try Promise
function foo(param, callback) {
return new Promise((resolve, reject) => {
request.get({
url: '',
headers: {}
}, (err, response, data) => {
array = []
data.forEach(function (entry) {
// do stuff with array
});
resolve(array)
});
})
}
module.exports.foobar = foo;
get resolve data
let param = 'some param';
foo(param).then(data=>{
// get your data here
});
Upvotes: 0
Reputation: 6908
Promise
s, and their related concept async/await, exist exactly for this purpose. Callbacks can get overly-nested if you're not careful, and this approach makes it simpler to flatten them down to one level. Both are standard in node 8 (stable).
Callbacks and promises are different patterns to do the same thing, and are compatible enough that you can simply wrap util.promisify around your existing callback.
const util = require('util');
const barAsync = util.promisify(bar);
// Wrap in an IIFE to get async support
(async () => {
let data = await barAsync('some param');
// do things using data...
data = await barAsync('some other param');
})();
Upvotes: 1