that is my raw response from API call who im trying to get each "bloc" result with a .forEach
const app = express();
const axios = require('axios')
jobList = [];
app.get('/getAPIResponse', function(req, res) {
async function myFunction() {
axios.get('https://api...')
//res.json(body)
.then((result) => {
result.results.forEach((element) => {
console.log(element)
this.jobList.push(element)
});
})
}
myfunction();
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
but the problem is, it made me some error on my terminal
(rejection id: 2)
(node:81826) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
at /Users/mac/Desktop/alternatics_test/index.js:22:24
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:81826) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:81826) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
at /Users/mac/Desktop/alternatics_test/index.js:22:24
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:81826) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 4)
to be as clear as possible results is the keyword in the api from which I would like to take each result block for insert in my "jobList"
I looked everywhere and the forEach seems to be the right technique for this...
You are using module axios
That will return a response with axios response schema
So you have to get result like this result.data.results then you can use forEach function
use result.data.results.forEach
Related
I'm using tesseract within my node app. The first time the program runs fine.
In this example, foo() repeats it self. From the first repition on, an error is returned (shown below the code)
Could you give me a hint what I have done wrong which doesn't allow this to run a second time? I have tried to add try & catch, but it only led to more errors
const { createWorker } = require('tesseract.js');
const worker = createWorker();
function foo() {
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
await worker.setParameters({
tessedit_char_whitelist: '123456789'
// preserve_interword_spaces: '0',
});
const { data: { text } } = await worker.recognize('Download.png');
console.log(text);
await worker.terminate();
})();
setTimeout(foo, 10000);
}
foo();
Error message:
(node:13988) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of null
at module.exports (\\node_modules\tesseract.js\src\worker\node\send.js:9:10)
at \\node_modules\tesseract.js\src\createWorker.js:47:7
at new Promise (<anonymous>)
at startJob (\\node_modules\tesseract.js\src\createWorker.js:43:5)
at Object.load (\\node_modules\tesseract.js\src\createWorker.js:57:5)
at \\tesseract3.js:28:18
at Timeout.myFetch [as _onTimeout] (\\tesseract3.js:38:5)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13988) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:13988) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:13988) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of null
Learning MVC, I'm trying to seed my database with dummy entries and I keep getting this error:
(node:19287) UnhandledPromiseRejectionWarning: Error
at Query.run (/Users/joshuaramat/Documents/projects/tech-blog/node_modules/sequelize/lib/dialects/mysql/query.js:52:25)
at /Users/joshuaramat/Documents/projects/tech-blog/node_modules/sequelize/lib/sequelize.js:313:28
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async MySQLQueryInterface.bulkInsert (/Users/joshuaramat/Documents/projects/tech-blog/node_modules/sequelize/lib/dialects/abstract/query-interface.js:335:21)
at async recursiveBulkCreate (/Users/joshuaramat/Documents/projects/tech-blog/node_modules/sequelize/lib/model.js:1655:25)
at async Function.bulkCreate (/Users/joshuaramat/Documents/projects/tech-blog/node_modules/sequelize/lib/model.js:1744:12)
at async seedAll (/Users/joshuaramat/Documents/projects/tech-blog/seeds/index.js:14:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:19287) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19287) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
the following is the code used to seed my data:
const seedUsers = require('./user-seeds');
const seedPosts = require('./post-seeds');
const seedComments = require('./comment-seeds');
const seedVotes = require('./vote-seeds');
const sequelize = require('../config/connection');
const seedAll = async () => {
await sequelize.sync({ force: true });
console.log('SEQUELIZE--------------');
await seedUsers();
console.log('USERS--------------');
await seedPosts();
console.log('POSTS--------------');
await seedComments();
console.log('COMMENTS--------------');
await seedVotes();
console.log('VOTES--------------');
process.exit(0);
};
seedAll();
The error seems to occur after the seedPosts() function is called.
Would anyone be able to help?
router.get('/:id', async (req, res) => {
const course = await Course.findById(req.params.id);
if (!course) {
return res.status(400).send(`course id is invaild`);
}
res.send(course);
});
As you guys can see, this is a very simple route function.
It works fine if it got the right id but once I gave it the wrong id it throws this error on my console
GET /api/courses/600f4aab118a6c5ef60fb5f7 200 75 - 20.069 ms
(node:32606) UnhandledPromiseRejectionWarning: CastError: Cast to
ObjectId failed for value "600f4aab118a6c5ef60fb5f7a" at path "_id"
for model "Course"
at model.Query.exec (/home/hesham/Desktop/test-express/node_modules/mongoose/lib/query.js:4358:21)
at model.Query.Query.then (/home/hesham/Desktop/test-express/node_modules/mongoose/lib/query.js:4452:15)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created) (node:32606)
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled
with .catch().
To terminate the node process on unhandled promise
rejection, use the CLI flag `--unhandled-rejections=strict` (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1) (node:32606) [DEP0018] DeprecationWarning: Unhandled
promise rejections are deprecated. In the future, promise rejections
that are not handled will terminate the Node.js process with a
non-zero exit code.
I'm using Node.js and Express to build a REST api. The database operations are in a separate file called "db.js". Here's the gist of the code:
...
const db = require('./db');
app.get('/b50api/workitems/me/:pernr', function (req, rs) {
db.getWorkItems("200805").then((items, output)=>{
console.log("ITEMS:", items);
console.log("OUTPUT:", output);
}).catch(err => {
console.log("ERROR:", err);
})
})
...
When I hit this endpoint the program fails with the error below.
I created a test .js file (below) and this runs just fine:
const db = require('./db');
function test() {
db.getWorkItems("200805").then((items, output)=>{
console.log("ITEMS:", items);
console.log("OUTPUT:", output);
}).catch(err => {
console.log("ERROR:", err);
})
}
test();
What am I missing??
Here's the error information when running in my REST api:
(node:14612) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(node:14612) UnhandledPromiseRejectionWarning: TypeError: p.callNotify is not a function
at C:\inetpub\wwwroot\PersonnelApps\b50api\node_modules\msnodesqlv8\lib\procedure.js:332:11
at C:\inetpub\wwwroot\PersonnelApps\b50api\node_modules\msnodesqlv8\lib\procedure.js:305:13
at C:\inetpub\wwwroot\PersonnelApps\b50api\node_modules\msnodesqlv8\lib\procedure.js:194:9
at runNextTicks (internal/process/task_queues.js:62:5)
at processImmediate (internal/timers.js:429:9)
(node:14612) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:14612) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Turns out the issue was it was attempting to connect to the database as some built-in account. I need to change the site to an application and change the account it's running under to the one that needs to authenticate to the SQL Server (along with making that same account one that can log on as a service).
Hello in my nodejs api i need fetch data inside the loop and then again need to do a loop and save a data in another table how should i achive that?
Here is some snippet that i have tried but not succeeded for the same
async myAPIname(){
let _this = this;
try {
const bets = await Bet.find({gameId:ObjectId(request.matchId)}).lean()
bets.map(async (bet) => {
let Users = await Users.findOne({_id:ObjectId(element.userId)}).lean();
Users.parentTree.map(async (user) => {
console.log(user);
// also over here based on the some calculation need to save the data in another table
})
})
} catch (error) {
_this.res.send({ status: 0, message: error });
}
}
Also in above snipped tried with foreach loop as well but not succeeded
and error from above spinet like this:
(node:30886) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'Users' before initialization
at /var/www/html/api/app/controllers/SomeController.js:228:30
at Array.map (<anonymous>)
at SomeController.myAPIname (/var/www/html/api/app/controllers/SomeController.js:227:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:30886) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:30886) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:30886) UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.
at /var/www/html/api/app/controllers/SomeController.js:220:27
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:30886) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Any Help will really appreciated
I can see two problems:
firstly the await inside a map call doesn't work like you think. It will work fine in a for-of loop but not in a map, foreach etc.
https://zellwk.com/blog/async-await-in-loops/ has a good an explanation as anywhere.
Secondly where you are calling let Users = Users.findOne, the compiler thinks that Users on the left hand side of the assignment is the same as the Users on the right hand side so it complains that when its calling Users.findOne, Users isn't initialised.
to use asynchronous handling with Array.prototype.map() you have to wrap it with Promise.all() and wait for it to fulfill.
!! however notice that iterations are executed in asynchronous way, not waiting for previous iteration to settle.
const sleep = async (time = 3000) => new Promise(resolve => setTimeout(resolve, time));
(async () => {
const array = [1,3,4,2];
console.log('start', array);
const mapped =await Promise.all(array.map(async e => {
await sleep(e * 1000);
console.log(e);
return `done for ${e}`;
}));
console.log('end', mapped);
})();