beginner node.js callback example [closed] - node.js

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm pretty novice in nodejs
This is a very easy php example that I want to write in nodejs
$key='foo';
$inside= openthedoor($key);
if(!$inside){ //wrong key
$key= getanewkey();//get a new key
$inside= openthedoor($key);//open the door again
}
How can I do this callback in nodejs?
appologies for the stupid question.

Keep in mind that you can still write things synchronously in Node.js, but if openthedoor() did happen to require a callback function, this is what it'd look like:
var key = 'foo';
openthedoor(key, function(inside) {
if (!inside) {
key = getanewkey();
openthedoor(key, function(inside) {
// check if we're inside again
});
}
});
A callback function is a function that is called on completion of another function. In the example, you are passing this function:
var callback = function(inside) {
if (!inside) {
// do something else
}
});
Into this function to be called when there is a result:
openthedoor(key, callback);

Related

How promises work in Typescript - I have error in mysql [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm working in an Angular 8.3 app with Node 10.17 and Mysql.
When I try to send information in JSON to the Backend I got an error in promises and I don't know what to do.
I've already investigated and I can't find the error
My code
In Angular Component.TS
async entrar(): Promise<void>
{
const datosJSON = JSON.stringify(
{
NombreP: "Fulanito",
ApellidoPa: "Perengano",
ApellidoMa: "merengano",
Calle: "ejemplo",
Numero: "9235",
Colonia: "ejemplo",
Municipio: "ejemplo",
CP: new Number(1234),
NumSeg: "595625634",
FechaNacimiento: "1234-56-78"
}
);
console.log(datosJSON)
await this.http.post('http://localhost:3000/alumnos/persona', datosJSON ).subscribe((data) =>{
this.datos= data;
console.log(this.datos);
})
}
Welcome to StackOVerflow!
The more details you give, the more accurate the answers you get.
I'm seeing a lot of misconceptions here:
You should not JSON.stringify your object, because then you'll be converting your object into a string. Usually in the POST request you just send the object as it is or in some other scenarios you can create a FormData
Observables are not Promises
You are not returning anything and certainly not a Promise.
Don't subscribe on your Service, if you really really need a promise here, consider:
return this.http.post('http://localhost:3000/alumnos/persona', datosJSON).toPromise()
Probably you don't need async/await here
this.datos = await this.http.post('http://localhost:3000/alumnos/persona', datosJSON ).toPromise();
In your case the data variable inside the subscribe method is returned when the observable is converted to Promise and awaited

How to catch messageBack in node.js [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am trying to use messageBack in Bot framework. (The reason is postBack is not supported for MS Teams and imBack shows the system message to the user. I also tried to use invoke but that function is no longer in the botbuilder library)
I found the function messageBack in the library botbuilder, but I dont know how to catch the action once user presses the button.
For imBack I can use this:
bot.dialog('catchOption', [
function (session, args, next) {
}
]).triggerAction({ matches: /choose-time-card[0-9]+-[0-9]+/i});
I tried invoke but this is said to be limited to "internal use" whatever that means. So I tried this but it doesnt work:
bot.on('invoke', function (event) {
var msg = new builder.Message().address(event.address);
msg.data.text = "I see that you clicked a button.";
bot.send(msg);
bot.send(JSON.stringify(event));
});
Does anyone know?
A few comments on this:
The SDK release from a few days ago 3.14 reinstated the Invoke ActionType.
To accomplish what you want to do it is as simple as something like this:
var bot = new builder.UniversalBot(connector, function(session) {
if(session.message.text === "your messageback value"){
//do stuff
}else{
session.send("You said: %s", session.message.text);
}
}).set('storage', inMemoryStorage);

What does underscore wrap function do? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Looking at the example given here (http://underscorejs.org/#wrap), I don't really understand what wrap is doing ... Even more so, when the function is "wrapped" it feels the parameters have to be set (for example, what about doing hello('john')? Are there other examples available that explains what wrap is all about? What would be a typical use case for it?
Thanks!
C
_.wrap() can accept more parameters in callback function other than the function you have. For example to make your hello('John') example work we need some modification on the example code to be
var hello = function(name) { return "hello: " + name; };
hello = _.wrap(hello, function(func,name) {
return "before, " + func(name) + ", after";
});
hello('John');

Files aren't deleted from Amazon S3 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
i'm using aws-sdk in nodejs, this is the part of the code that delete the files:
var s3_params = {
Bucket: util.getEnvVar('AWS_S3_BUCKET'),
Delete: {Objects: [{Key: document.bucket_path }]}
};
s3.deleteObjects(s3_params, function (err, data) {
if (err) {
res.send(err);
} else {
res.send(data);
}
});
The response that return from amazon look fine, but when i look on the bucket inside the s3 interface the file still exist.
also try to use "deleteObject" method with no success.
Thanks.
The code looks good. Are you sure you are passing a Key of a file that exists? Beware that if you try to delete a Key that does not exist, AWS won't throw an error, check this question.

Engine.IO tutorial needed [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
Hi I am trying to use Engine.IO.
As stated here on StackOverflow it is supposed to be low level version of Socket.IO. Also it supposed to be better and newer. Also it should give me the ability to easily exchange messages between browser client and Node.js server. Doh.
I read from top to bottom these two pages:
https://github.com/LearnBoost/engine.io
https://github.com/learnboost/engine.io-client
But it does not help, those manuals seem to be written for somebody who already know how to use the technology not for somebody who is trying to learn it. Even the basic parts are missing.
How the client script is supposed to get to the browser?
What is the landing address for the "hello world" I should type in the browser?
Step-by step instruction to got started?
Please help! This is not easy when you try to learn something like that!
This is what the client script supposed to be:
<script src="/path/to/engine.io.js"></script>
<script>
var socket = new eio.Socket('ws://localhost/');
socket.on('open', function () {
socket.on('message', function (data) { });
socket.on('close', function () { });
});
</script>
But now what is that? Index.html? What does it all mean? How to use it?
Now here is the "server" part:
(A) Listening on a port
var engine = require('engine.io')
, server = engine.listen(80)
server.on('connection', function (socket) {
socket.send('utf 8 string');
});
(B) Intercepting requests for a http.Server
var engine = require('engine.io')
, http = require('http').createServer().listen(3000)
, server = engine.attach(http)
server.on('connection', function (socket) {
socket.on('message', function () { });
socket.on('close', function () { });
});
(C) Passing in requests
var engine = require('engine.io')
, server = new engine.Server()
server.on('connection', function (socket) {
socket.send('hi');
});
// …
httpServer.on('upgrade', function (req, socket, head) {
server.handleUpgrade(req, socket, head);
});
httpServer.on('request', function (req, res) {
server.handleRequest(req, res);
});
Why is this broken in three parts? Which one corresponds to the client example? Maybe I sound dumb, but how to get the "hello world" going?
I would suggest you read the following book , it will clear out some of your concerns.
"http://www.nodebeginner.org/".
Then try to make your first NodeJS App just doing what the book says , so that you get a bit the idea behind it.
After that go on and use "socket.io" and create a simple app with the help of this tutorial "http://net.tutsplus.com/tutorials/javascript-ajax/real-time-chat-with-nodejs-socket-io-and-expressjs/".
After that i believe you will not have any questions regarding engine.io and you will be able to go on with your project.
Jumping to engine.io without prior knowledge of "NodeJS" and "socket.io" has a hard learning curve.

Resources