This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I just started learning Javascript and I was wondering how can I use the portfinder.getPort() function in one of my functions to get a random port every time. This is my code right now:
var portfinder = require('portfinder')
portfinder.getPort(function (err, port) {
var p = port;
});
function toAddress (name) {
return name + p;
}
I know this is wrong but how can I use it?
Thanks in advance.
You should check the usage example on the project's Github page:
There is also examples on the NPM Page
From the docs:
var portfinder = require('portfinder');
portfinder.getPort(function (err, port) {
//
// `port` is guaranteed to be a free port
// in this scope.
//
});
In your code the problem seems to be the way your accessing p is not correct, because it's in a closure and not available outside of the scope of that function.
If you move the declaration of p outside the closure you can then access it from the other function but a better way would be to pass it to toAddress.
Related
This question already has answers here:
How to mock functions in the same module using Jest?
(10 answers)
Closed 6 months ago.
Consider this set of code snippets where I want to write unit tests for function A, which internally calls function B during execution. Assume B is a set of API calls for validation that I want to mock return value to true.
But this spyOn method approach does not work, and the API calls in B still get executed. I've seen approaches with mocking the complete module with jest.requireActual(), but they do not seem to work too.
What could be a better way to test such functions without changing a lot in the codebase index.ts?
//index.ts
async function A (a:string, b:string, c:string) {
// code
await B(data);
// code
}
async function B (data:customType) {
//code
//API calls
//code
}
export default {
A,
B }
//index.test.ts
import index from '../index.ts';
describe('Test suit', ()=>{
it('should be a test for function A', async ()=> {
jest.spyOn(index, 'B').mockReturnValue(true);
// code
const result = await index.A('a','b','c');
// code
})
})
There is not really a good way to do it, when the functions are in the same module with jest only.
But you can with Rewire, it's explained in this answer and worked very well in a similar situation for me: https://stackoverflow.com/a/52725067/16068019
Otherwise if it's an option you could move one of your functions to a different module, but that's not always an option.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 4 years ago.
Im exploring vue and new javascript tools - things are a bit convoluted for me, in the sense I struggle to debug and understand what is going on.
I am trying to fetch data via a simple API, using axios as suggested here:
https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#Real-World-Example-Working-with-the-Data
turns out, if I use "normal" javascript, data will not be set.
It must have something to do with interpreting "this" element.
Instead, if I use arrows functions, data are set.
data () {
return {
query : {
info : null
}
}
methods : {
test : function(query) {
params = {
origin : '*',
action : 'query',
prop : 'pageimages',
pithumbsize : 400,
pilimit : 'max',
list : 'search',
srsearch : query,
utf8 : true,
format : 'json'
}
axios.get('https://en.wikipedia.org/w/api.php', {
params : params
})
.then(function (response) {
// won't work : this.query.info // undefined
this.query.info = response.data.query.search
})
.then(
// this.query.info is set
response => {
this.query.info = response.data.query.search
}
)
}
}
Can you explain why?
I helped myself with answer in :
What does "this" refer to in arrow functions in ES6? - "this refers to the enclosing context" :
what does this refer to in the pattern then(function(response){ this.[...]) and in the patter then( response => this.[...]) ?
how could I use syntax without arrows functions, and use this referring to the data() model of vue ?
Would you mind to also suggest working practices to keep code clean and simple?
I came from using native javascript and jquery, and despite a bit more verbose, I could understand well what was going on and easily debug.
Instead with these new tools, despite powerful, I am a bit lost for it seems there is an overload of other tools to use to get things done.
While learning I still would prefer to code a bit more verbosely and use web console to debug, instead of nodes plugin and syntax that must be compiled by frameworks.
__
Edited
Upon comments, I tried:
.then(function(response){
// won't work : here thisArg should be the vue app,
// so self.query.info should bind to
// [App data()].query.info
// still, query.info is undefined
// though response was successfully fetched
var self = this
self.query.info = response.data.query.search
})
Edited 2 (Answer)
I found this answer helpful:
https://stackoverflow.com/a/29881419/305883
so I realised above patter was wrong, for writing var self =this within the then() means I am still referenceing the this of the promise object, which is undefined.
so with "normal" functions, I should write something like:
var self = this; // now self is referenced to the external object, the Vue app
fetchResponseFromApi(query)
.then(function(response){
self.query.info = response.data.query.search
})
This answer address my question (no pun for "this" answer, hohoho :).
In other answers I read comments not to pass around the thisArg, like into encapsulated functions:
comments about clarifying about good coding patterns will be of good for others to.
This question already has answers here:
How to avoid long nesting of asynchronous functions in Node.js
(23 answers)
Closed 6 years ago.
I'm new in js. In my project I'm using mysql and node js.
Somewhere in controller I need to get some data from differnet models. In php it looks like
function some() {
$user = $user->getOne($id);
$photos = $photos->getOne($user->id);
$posts = $post($user->id, $photo->uid)
}
and I have all this variables in one scope
in node js result of model is async, so it's look like nestings callbacks.
Short example
UserModel.findbyid(result.user_id, function (err, user_data) {
PhotoModel.GetVoteCount(user_data.id, result.id, function (res_count) {
PhotoModel.getWinners(function (err, winners_ar) {
PhotoModel.getweekusers(1, function (result_week) {
response.render('one.twig', {
view_user: request.user,
image: result,
p_user: user_data,
count: res_count,
winners: winners_ar,
week_users: result_week['photos']
});
});
})
});
});
so I have nested callbacks, I feel it's not right way to code, can you explain best practices?
You have two options :
Use async module (async)
Use a library which returns promises (like promise-mysql).
You can take a look at async module
This simplifies what you call "callback hell" through some functions that helps create flows in async code.
Specifically to your case - async.waterfall will do the trick
Use promises,or libraries that will help you use promises.
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 7 years ago.
I'm using Sails.js framework and its great Model's feature, also I'm using the async version it uses as its dependency.
So, in order of explaining a practical scenario: get all comments on songs sung by an artist. I should first query the songs and then, query against comments.
This why I'm using async module, in particular its waterfall function. But as all this code is placed at a Model file, where this refers to the model itself, I got one big doubt:
Will this always refer to the model even when present inside async functions?
This is a code example of what I'm doing:
module.exports = {
connection: 'seasonDB',
attributes: {
reachesMaxFavoriteTeam: function (team) {
var results [];
async.waterfall([
// Get favorite team
function (cb) {
var userTeam = this.userTeam;
UserTeam.findOne({_id: userTeam}, function (err, foundUserTeam) {
if (err)
cb(err,null);
var user = foundUserTeam.user;
User.find({_id: user}, {_id:false, fanOf: true}, function (err, fanOf) {
if (err)
cb(err,null);
cb(null,fanOf.name);
});
});
},
// Check if it reaches a max favorite team error
function (favoriteTeam,cb) {
// If player to be added is from favorite team, it counts.
favoriteCount = team === favoriteTeam ? 1: 0;
// Check if any of added players are from favorite team too.
_.forEach(this.players, function (player) {
var playerTeam = player.team.name;
if (playerTeam === favoriteTeam)
favoriteCount++;
});
return favoriteCount > process.env.CONDITION;
}]);
}
};
So, for example, at the first function in waterfall series I got: var userTeam = this.userTeam;, will this work as expected? Should I take care of something in case of other nested functions?
Why don't you use Promises in those queries will make it so much easier to work with. I wouldn't use async, using Promises should do the job.
The underlying ORM module in Sails is Waterline. You can refer to Chaining waterline calls with Promises for an example or the GitHub page https://github.com/balderdashy/waterline which shows the below example,
User.findOne()
.where({ id: 2 })
.then(function(user){
var comments = Comment.find({userId: user.id}).then(function(comments){
return comments;
});
return [user.id, user.friendsList, comments];
}).spread(function(userId, friendsList, comments){
// Promises are awesome!
}).catch(function(err){
// An error occurred
})
Waterline-docs is also helpful for reference: https://github.com/balderdashy/waterline-docs
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the purpose of NodeJS module.exports and how do you use it?
I have the following code:
var express = require('express');
var app = module.exports= express();
require('./config/environment.js')(app, express, __dirname);
require('./routes/default.js')(app, __dirname);
module.exports = function (app, express, dirname) {
....
};
module.exports = function (app, dirname) {
....
};
what happened in this code. Second string says, that module.exports and app are the same object, right?
but in function(...) parts app pass as parameter and that code likes on "to object 'module' add method 'exports' and do it 2 times" I want to add some functions, which want to use inside each function (...), but can't because don't understand what happens in that constructions.
Thanks
Why are you assigning module.exports three times? In your code module.exports will first become equal to what ever is returned by calling express. Then module.exports will become equal to your function (NOT what it returns) and will take 3 arguments. Then module.exports will be equal to your final function (again NOT what it returns) taking 2 arguments. Therefore by the end of your code module.exports will be equal to that final function. So I don't see what the need is for the first two assignments. App will be equal to module.exports at the end because app is pointing to module.exports the whole time. It doesn't matter that you want app to be passed as an argument to it because no where in the code above do you actually pass app into the function, after assigning the functions to module.exports. All you have done here is name a parameter "app".
I think you have either missed code out here or got very confused by other languages you may have used in the past.
Lookup Douglas Crockford if the language isn't clear to you.
I hope that helps.