[英]Wait for async process to finish before redirect in koajs
我目前正在嘗試生成一個子進程來使用NodeJS(使用Koa框架)處理一些POST數據。
理想情況下,我想在重定向之前等待子進程完成,但是由於子進程是異步的,因此代碼始終首先重定向。 我一直在嘗試修復此問題很長時間,並提出了一些新穎的方法來部分解決它,但是沒有什么非常干凈或可用的。
處理此問題的最佳方法是什么?
以下是我發布路線的功能(使用koa-route中間件)。
function *task() {
var p = spawn("process", args);
p.on("data", function(res) {
// process data
});
p.stdin.write("input");
this.redirect('/'); // wait to execute this
}
為了等待在koa中完成同步任務/操作,您必須yield
一個帶有回調參數的函數。 在這種情況下,要等待子進程完成,必須發出“退出”事件 。 雖然您也可以偵聽其他子進程事件,例如close
或標准輸出的end
事件。 它們在退出之前發出。
因此,在這種情況下, yield function (cb) { p.on("exit", cb); }
yield function (cb) { p.on("exit", cb); }
應該起作用,我們可以減少它yield p.on.bind(p, "exit");
使用Function::bind
function *task() {
var p = spawn("process", args);
p.on("data", function(res) {
// process data
});
p.stdin.write("input");
yield p.on.bind(p, "exit");
this.redirect('/'); // wait to execute this
}
您還可以使用幫助程序模塊來幫助您: 共同子過程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.