Comments (5)
@AleksMeshkov yep, basically the same approach I ended up with. Cheers.
from discussions.
Hummm...
This is not exactly Koa issue (IMO)!!
You can use worker_threads
to avoid blocking code and keep chaining flowing.
And your code will be consistent!
// thread-service.js
'use strict'
const {Worker, isMainThread} = require('worker_threads')
function runService(service, workerData) {
if (isMainThread === false) {
return
}
const worker = new Worker(service, {workerData})
worker.once('message', console.log)
worker.once('exit', code => {
worker.removeAllListeners()
worker.terminate()
if (code !== 0) {
new Error(`Worker stopped with exit code ${code}`)
}
})
}
module.exports = runService
// service.js
'use strict'
const {workerData, parentPort} = require('worker_threads')
// const db = require('./my-db')
;(async () => {
try {
// do your stuff with data
// const result = await db.save(workerData)
console.log('thread --->', workerData)
const result = Math.random()
parentPort.postMessage({result})
process.exit(0)
} catch (error) {
process.exit(1)
}
})()
// app.js
'use strict'
const {join} = require('path')
const Koa = require('koa')
const runService = require('./thread-service.js')
const app = new Koa()
app
.use(async (ctx, next) => {
const start = Date.now()
ctx.state.start = start
console.log('start --> goto b')
await next() // goto b
// a
const ms = Date.now() - start
ctx.set('X-Response-Time', ms)
console.log('a --> end')
})
.use(async (ctx, next) => {
// b
const {start} = ctx.state
// start thread and keep running
runService(join(__dirname, 'service.js'), {start})
console.log('b --> goto c')
await next() // goto c
// b2
// goto a
console.log('b2 --> goto a')
})
.use(ctx => {
// c
ctx.body = {ok: true}
// goto b2
console.log('c --> goto b2')
})
.on('error', console.error)
app.proxy = true
app.listen(3435, () => {
console.log('Running: http://[::1]:3435')
})
Output
> node app.js
Running: http://[::1]:3435
start --> goto b
b --> goto c
c --> goto b2
b2 --> goto a
a --> end
thread ---> { start: 1587672397920 }
{ result: 0.5918108149573942 }
from discussions.
Same thing, I can't manage to respond immediately and continue function execution.
public static async orderFulfilled(ctx: Context, next) {
// need to immediately respond (in 5 seconds or so) otherwise they assume this request failed
ctx.status = 200;
ctx.body = 'ok';
await next();
// do the math.......
}
This doesn't work!
from discussions.
Here is the feedback I ended up getting: https://stackoverflow.com/a/60877855/1172519.
By the time I got a response I just ended up refactoring the "middleware" called by the server route as a sync (note: non-async) function (not middleware at all at this point due to the fact that a single sync method has to do all the work).
So I haven't tested the linked answer, but it appears to be a great way to establish general error handling for Koa.
However, I don't understand why this needs to be so hard.
from discussions.
Hey @paulisloud!
Thanks for the tip! I finally achieved what I wanted without (adding additional) / (restructuring existing) middleware. Here's my solution for this:
// THE ROUTE METHOD, THE INITIAL ENTRYPOINT.
public static async orderFulfilled(ctx: Context, next) {
// need to immediately respond (in 5 seconds or so) otherwise they assume this request failed
ctx.status = 200;
ctx.body = 'ok';
await next();
// do the math.......
// calling timeDemandingTask WITHOUT AWAIT
timeDemandingTask();
}
// OUR TIME DEMANDING METHOD WE DON'T WANT TO WAIT
private static async timeDemandingTask(ctx: Context) {
// doing the math.......
await action_1();
await action_2();
await action_3();
await action_4();
// two minutes passed!
}
In the end it works as intended.
from discussions.
Related Issues (20)
- Move koa modules into this organization HOT 1
- ctx.req.on and ctx.req.pipe limitations ?
- Hosting mp3 file HOT 2
- Why Koa ctx.body not working in if statement? HOT 3
- EPIPE error occurs when the server returns mp3 file. HOT 1
- Cannot make middleware to coerce type of query parameter HOT 1
- Question on inheriting Koa HOT 1
- How to exclude api router? HOT 1
- Access to XMLHttpRequest at 'https://localhost:3443/images' from origin 'http://localhost:4200' has been blocked by CORS policy
- Conditional middleware
- Hosting mp3 file
- Either 404 or wrong content HOT 1
- [koa] Unexpected exit with code 0 during an http request HOT 4
- Using both koa-compress and koa-static , extremely slow when visit static files from 127.0.0.1 or localhost (from public address is fast), why? HOT 2
- Brotli compress is slow HOT 2
- @fl0w becomes @miwnwski HOT 1
- How can I catch EADDRINUSE? HOT 5
- Uncaught `TypeError: Cannot read property 'hasHeader' of undefined` error
- Why the request url parameter + is turned into a space? HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from discussions.