onTimeout and is not function error using node js

Viewed 41

I am trying to call an async function inside the setInterval by passing two arguments originalDetails and filePath. so I created a function with the name createUser and in the same function, I am adding the setInterval with 3 sec as finDetails() needs some delay to execute that function. I am getting the error as await self.gotUser(originalDetails) is not a function. Why I am getting this error I don't know

my code is as follows:-

const findDetails = require("./findDetails");

async createUser(originalDetails,filePath){
 return new Promise(async (resolve reject)=>{
  
  findDetails(filePath);

  setInterval(this.findUser,3000,originalDetails,filePath);
 })
}

async findUser(originalDetails,filePath){
 return new Promise(async (resolve reject)=>{
  // some code here

  var self=this;

  await self.gotUser(originalDetails); // I am getting error here in this part
  return resolve();
 });
}

async gotUser(originalDetails){
 return new Promise(async (resolve, reject)=>{
 let inputValue;
 // some coding part here

 return resolve();
 });
}

I have tried the code by writing both self and this still I'm getting the same issue

and this is my error message look likes

error message

/Users/servive_project/provide_service.js:300:18
      await self.gotUser(originalDetails);
                 ^

TypeError: self.gotUser is not a function
    at /Users/servive_project/provide_service.js:300:18
    at new Promise (<anonymous>)
    at Timeout.createUser [as _onTimeout] (/Users/servive_project/provide_service.js:288:12)
    at listOnTimeout (node:internal/timers:561:11)
    at processTimers (node:internal/timers:502:7)

getting two error at a same time

  1. self.gotUser is not a function.
  2. Timeout.createUser [as _onTimeout].
2 Answers

you could change the way you call setInterval so you call this.findUser with this being your instance. Then you could get rid of the self trick in findUser.

setInterval(
  () => this.findUser(originalDetails, filePath), // use arrow function so 'this' context is still your class instance.
  3000
);

Capture your this outside the promise.

async findUser(originalDetails,filePath){
 var self=this;

 return new Promise(async (resolve reject)=>{
  // some code here

  await self.gotUser(originalDetails); // I am getting error here in this part
  return resolve();
 });
}
Related