Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

Multithreading in Node.js: How to return a response from Router, but perform other operations in a separate thread?

I have a get route using router that needs to perform multiple time consuming operations (the duration of which usually cause Postman or whatever queries my backend to timeout). I want to return some JSON response, but then also continue to perform other operations in a separate thread. These operations will write to my database so I understand that they won't be included in the request response.

Here is my code:

router.get('/test', async (req, res) => {
    await querySources(req.query.id, req.query.name) // this operation takes a very long time, and has no effect on return value
    return res.status(500).json({message: "success"})
}

I tried putting the querySources call in an async block like this:

async () => {
    querySources...
}

but it never gets called


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you don't want the response to wait for the database operation to complete, then you can do either of these:

// remove the await so you don't wait for the query to finish
router.get('/test', (req, res) => {
    querySources(req.query.id, req.query.name).catch(...)
    res.status(500).json({message: "success"})
}

or

// send the response immediately, then do the database stuff
router.get('/test', (req, res) => {
    res.status(500).json({message: "success"})
    querySources(req.query.id, req.query.name).catch(...) 
}

Note, you will need some ability to catch any error that querySources() has so that error doesn't go unhandled. Probably you just need to log it since the client can't be notified at this point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...