Firstly, I am very new to node.js and I just started learning about callback function. So, I came to know that callback function basically works to handle multiple requests.
Then I thought of writing a function to see how it normally works without using callback function and I am getting an error here.
[Screenshot of the output][1]
https://i.stack.imgur.com/30AvR.png
Here, I thought it would work like :
Every 5 seconds it would display
Order placed : 1
Delivered food with order number: 1
.
...
....
....
Delivered food with order number: 6
To achieve expectation you should use async series method
Please refer below stackoverflow
Nodejs async series - pass arguments to next callback
Related
I am still quite new to Node.js and can't seem to find anything to help me around this.
I am having an issue of getting the query from my last record and adding it to my variable.
If I do it like below: -
let lastRecord = Application.find().sort({$natural:-1}).limit(1).then((result) => { result });
Then I get the value of the variable showing in console.log as : -
Promise { <pending> }
What would I need to do to output this correctly to my full data?
Here is it fixed:
Application.findOne().sort({$natural:-1}).exec().then((lastRecord) => {
console.log(lastRecord); // "lastRecord" is the result. You must use it here.
}, (err) => {
console.log(err); // This only runs if there was an error. "err" contains the data about the error.
});
Several things:
You are only getting one record, not many records, so you just use findOne instead of find. As a result you also don't need limit(1) anymore.
You need to call .exec() to actually run the query.
The result is returned to you inside the callback function, it must be used here.
exec() returns a Promise. A promise in JavaScript is basically just a container that holds a task that will be completed at some point in the future. It has the method then, which allows you to bind functions for it to call when it is complete.
Any time you go out to another server to get some data using JavaScript, the code does not stop and wait for the data. It actually continues executing onward without waiting. This is called "asynchronisity". Then it comes back to run the functions given by then when the data comes back.
Asynchronous is simply a word used to describe a function that will BEGIN executing when you call it, but the code will continue running onward without waiting for it to complete. This is why we need to provide some kind of function for it to come back and execute later when the data is back. This is called a "callback function".
This is a lot to explain from here, but please go do some research on JavaScript Promises and asynchronisity and this will make a lot more sense.
Edit:
If this is inside a function you can do this:
async function someFunc() {
let lastRecord = await Application.findOne().sort({$natural:-1}).exec();
}
Note the word async before the function. This must me there in order for await to work. However this method is a bit tricky to understand if you don't understand promises already. I'd recommend you start with my first suggestion and work your way up to the async/await syntax once you fully understand promises.
Instead of using .then(), you'll want to await the record. For example:
let lastRecord = await Application.find().sort({$natural:-1}).limit(1);
You can learn more about awaiting promises in the MDN entry for await, but the basics are that to use a response from a promise, you either use await or you put your logic into the .then statement.
I have seen three ways to return a JSON object or end a Lambda function. My trigger is Smart Home Alexa.
I am using now is context.succeed(response_JSON);This one works for me. Even if this instructions is inside a nested function. The whole Lambda ends and return the response_JSON to Smart Home Alexa.
I have seen in other blogs that say callback(response_error,response_JSON). This one did not work for me. It did not return anything to Smart Home.
Others just uses the return response_JSON. I have not used this one.
I am using now is context.succeed(response_JSON);This one works for me. Even if this instructions is inside a nested function. The whole Lambda ends and return the response_JSON to Smart Home Alexa.
context.succeed()/fail() causes the Lambda function to terminate immediately. However, I have not seen this documented in the context object docs, so it may get deprecated in later Node versions (?).
I have seen in other blogs that say callback(response_error,response_JSON). This one did not work for me. It did not return anything to Smart Home.
This one probably doesn't work for you because by default Node.js waits for the event loop to be empty before executing the callback statement. This may be due to open network/database connection. As per the doc, set the context.callbackWaitsForEmptyEventLoop variable to false to send the response right away.
Others just uses the return response_JSON. I have not used this one.
This should be used with async handlers. Read more about async and non-async handlers here: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html
I'm wanting to force a test returns failure, bring success, why this?
I am using the proctrator and I need to wait for a data that comes from the server to the screen, however I have to update the page every 1 minute, I could not do something that updates and at the same time wait for the answer, I had to make a "for" execute a promise with loop that repeats 14 times, which gives a total of 14 minutes and every minute it refreshes the page, when it arrives the dice throws me an exception that can end before the loop is over, so that I can move on to the next test .
To not fail in my test, I would like this exception to be true, but I could not put a function in the jasmine to modify it, I have a very simple example of what I would like to do.
describe('Start simulator False', () => {
it('expect a fake to turn true ', () => {
const addition = 5 + 5;
expect(addition).toBe(2);
});
});
This expectation that expects 10 instead of 2, I would like instead of seeing a fake would like to see a truth, I know it is wrong but I can create a unique function that only I can use when ignoring its basic logic because I I know it's true and the only alternative I have is this.
You can create your own custom equality testers. See the documentation : https://jasmine.github.io/tutorials/custom_equality
But i will replace the jasmine equality tester.
So maybe you want to add your own matcher : https://jasmine.github.io/tutorials/custom_matcher
I'm just getting started in programming and am using VSC and installed Node and am using it to run my files. My console.logs works, but I can't get return values when I invoke functions. What am I doing wrong?
Node.js is asynchronous. 99% of all functions you write are going to be "non-blocking". If you don't quite understand what that is, I highly suggest you google up on the node.js event loop, and what it means to be "asynchronous".
Once you figure that out, start using the async/await syntax, or "promise" syntax.
Edit:
I see you posted more information. Based on what you're doing, it actually has nothing to do with being asynchronous.
The problem is that you're just returning a string value of hihihihihi... and that's it. You don't print it out anywhere. You need to wrap your call to function a() inside console.log(). So like: console.log(a());
I'm trying to scrape a webpage with nightmareJS and got stuck.
In my program i pass to the function an array on links which i need to the same data from all of them
The list can be very long (over 60) and if i try to do a
async.each(Links, function (url, callback) {
var nightmare = Nightmare(size);
...
}
Only the first couple few instances actually return a value , others just hang up and wont load (blank page).When i try to do only three it work perfectly.
How can i fix it? How can i redistribute the work , for example three in parallel and only when all done it will do the next set? One more thought maybe use the same instance and repeat the steps for all the links?
There are two possible solutions:
using eachSeries which waits until one operation is done before launching the other one.
Or in async.eachpass another argument which limits how many operation are running in the same time.