-2

I am looking for a solution for a problem in Node.js. Please help !

I have a router "find user", if user is existed in db continue do taskFunc(), else response error. But, my taskFunc() must take many time to complete, because each 30 seconds it will do a task.

I want to after check user exist, must response to client immediately, taskFunc() just run on server, if has error then throw.

router.post('/router1, function(req, res){
    var username = body.username

    User.find({where: {username: username}})
    .then(function(_data){
        if(_data){
            return taskFunc()
        }else{
            res.status(400).end()
        }
    })
})

var taskFunc = function(username){
    // function này thời gian xử lý mất nhiều thời gian
    // vì nó cứ nghỉ khoảng 30s mới thực hiện 1 nhiệm vụ khác
}
Nam Tran Thanh
  • 821
  • 2
  • 8
  • 14

2 Answers2

0

I think you are looking something as below:

router.post('/router1, function(req, res){
var username = body.username

User.find({where: {username: username}})
.then(function(_data){
    if(_data){
         setTimeout(taskFunc, 0)
         res.status(200).end()
    }else{
        res.status(400).end()
    }
})
})

var taskFunc = function(username){
// function này thời gian xử lý mất nhiều thời gian
// vì nó cứ nghỉ khoảng 30s mới thực hiện 1 nhiệm vụ khác
}

See here for detail on setTimeout: https://nodejs.org/docs/v0.6.1/api/timers.html

Deepak Bhatia
  • 1,090
  • 1
  • 8
  • 13
0
User.find({where: {username: username}})
.then(function(_data){
    if(_data){
        taskFunc()
        res.status(200).send('ok')
    }else{
        res.status(400).end()
    }
})

If i understand correctly, you just want to to send response and run the task in the background?

If so, just do res.status(200).send('ok')

Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54