node-webcam icon indicating copy to clipboard operation
node-webcam copied to clipboard

Promise support

Open Richienb opened this issue 5 years ago • 4 comments

It would be useful if promises were supported.

Richienb avatar Aug 20 '20 01:08 Richienb

I ended up creating a wrapper:

async function capture () {
	return new Promise((resolve, reject) => {
		NodeWebcam.capture('pic', cameraSettings, async (err, data) => {
			if (err) {
				return reject(err);
			}

			return resolve(data);
		});
	});
}```

knapcio avatar Nov 03 '20 11:11 knapcio

Agreed, once you use Promises you never want to go back to callbacks.

chuckfairy avatar Nov 08 '20 02:11 chuckfairy

nodejs has native promistify , probably best to use that https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original

const util = require('util');
const capture = util.promisify(NodeWebcam.capture);

async function cap() {
  const data = await capture('pic', cameraSettings)
}

didn't check that but something like this. But agreed, "native" promise support is must nowadays

gbkwiatt avatar Jan 07 '21 11:01 gbkwiatt

nodejs has native promistify , probably best to use that https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original

const util = require('util');
const capture = util.promisify(NodeWebcam.capture);

async function cap() {
  const data = await capture('pic', cameraSettings)
}

didn't check that but something like this. But agreed, "native" promise support is must nowadays

Tried this:

const util = require('util');
var NodeWebcam = require( "node-webcam" )

// Event loop
async function eventLoop() {
	// Create the webcam 
	const Webcam = NodeWebcam.create( opts )
	// Promisify
	const capture = util.promisify(Webcam.capture)
	// Start loop
	while(true) {
		// Record frame
		const buffer = await capture('.pic.jpeg')
		console.log('buffer', buffer)
	}
}

Results in error:

/.../node_modules/node-webcam/src/Webcam.js:221
        var fileType = Webcam.OutputTypes[ scope.opts.output ];
                                                 ^

TypeError: Cannot read properties of undefined (reading 'opts')
    at capture (/.../node_modules/node-webcam/src/Webcam.js:221:50)
    at node:internal/util:360:7
    at new Promise (<anonymous>)
    at capture (node:internal/util:346:12)
    at eventLoop (/..../index.js:51:24)
    at Object.<anonymous> (/..../index.js:65:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)

tamis-laan avatar Jan 26 '22 14:01 tamis-laan