promise.then()和promise.catch()在节点程序中不起作用

时间:2018-12-03 08:21:35

标签: javascript node.js opencv events es6-promise

我正在尝试显示一个实时流,该流由opencv4nodejs读取并由面部识别模块处理。这里的问题是,promise.then()无法正常工作。甚至没有在相应条件下使用catch()。(我是node和promises的新手。) 预期的工作流程:

  

从网络摄像头读取帧(通过cv.read)->保存到缓冲区(通过cv.imwrite)->   从缓冲区读取帧(通过fr.loadImage)->处理(通过detector.locateFaces)->显示->重复处理。

const fr = require('face-recognition');
const cv = require('opencv4nodejs');
const events = require('events');

const detector = fr.FaceDetector()
const cap = new cv.VideoCapture(0);
const win = new fr.ImageWindow()
const eventEmitter = new events.EventEmitter();

function process(){
    console.log('process');
    return new Promise(function(resolve,reject){
        console.log('promise');
        var frame = cap.read();
        cv.imwrite(`${__dirname}/buffer/img.jpg`, frame);
        if(frame != null)
            resolve('resolve');
        else
            reject('Problem While reading');
    });
}
eventEmitter.on('read',function(string){
    console.log('event call');
    var promise = process();
    promise.then(function(string){
        console.log(string);
        const image = fr.loadImage(`${__dirname}/buffer/img.jpg`);
        const faceRectangles = detector.locateFaces(image);
        win.setImage(image);
        fr.hitEnterToContinue();
    }).catch(function(err){
        console.log(err);
    });
});
while(true){
    console.log('emit');
    eventEmitter.emit('read','abcd');
}
/*****expected output should be*****
emit
event call
process
promise
resolve
/*****getting output*****
emit
event call
process
promise
*/

2 个答案:

答案 0 :(得分:0)

由于您正在使用eventEmitter,因此代码应如下所示:

ps-tree

答案 1 :(得分:0)

text = str(datetime_object.tm_hour)+"-"+str(datetime_object.tm_mday)+"-"+str(datetime_object.tm_mon)+"-"+str(datetime_object.tm_year)
> '0-28-2-1983'

更改: 1)从const fr = require('face-recognition'); const cv = require('opencv4nodejs'); const events = require('events'); const detector = fr.FaceDetector() const cap = new cv.VideoCapture(0); const win = new fr.ImageWindow() const eventEmitter = new events.EventEmitter(); function process(){ console.log('process'); return new Promise(function(resolve,reject){ console.log('promise'); var frame = cap.read(); cv.imwrite(`${__dirname}/buffer/img.jpg`, frame); if(frame != null) resolve('resolve'); else reject('Problem While reading'); }); } eventEmitter.on('read',function(string){ console.log('event call'); var promise = process(); console.log(promise); promise.then(function(string){ console.log(string); const image = fr.loadImage(`${__dirname}/buffer/img.jpg`); const faceRectangles = detector.locateFaces(image); console.log(faceRectangles); win.setImage(image); // fr.hitEnterToContinue(); eventEmitter.emit('read','abcd'); }).catch(function(err){ console.log(err); }); }); eventEmitter.emit('read','abcd'); 中删除while循环 2)在eventEmitter.emit('read','abcd');中递归发射事件 我观察到发出事件时连续发出promise.then()不起作用,所以我在promise.then()中发出事件,所以现在它很好地工作了。