简体   繁体   中英

Node.js thermal printer issue in loop printing

I am developing a web application in Laravel, which sends a list of articles via JSON to a process running on Node.js (i use websocket library), which must for each of these items call a print function (i use escpos library).

When i print one or two items there are no problem, and all its OK. But when i send 3 or more items, the printer print the first ok, but with the rest it have problems. I think when i send 3 or more items, the printer is too slow and can't end the jobs.

This is the part of my code in Node.js that print the items:

for (var i = 0; i < msg.items.length; i++) {
        for (var j = 0; j < msg.items[i].quantity; j++) {
          print(msg.items[i]);
        }
    }

(Note i use 2 loop because a item can have a quantity > 1 and i have to print 1 ticket for each item and quantity)

And this is the code of the printing library ( irrelevant but i leave it to clarify)

function print(item){

escpos.Image.load(__dirname + '/logo3.png', function(image){
    printer
    .raster(image)

    .control('LF')

    .style('b')
    .size(2, 2)

    .text(item.code)
    .control('LF')
    .control('LF')
    .barcode(item.ean, "EAN8")
    .cut();

});

I hope you can help me, thank you in advance.

I found a solution to the problem. I decided to use asynchronous requests with a timeout to wait for the printer to complete each task, along with promises. The code fragment:

function asyncFunction (item, cb) {
        setTimeout(() => {
            print_product(item);
            console.log("Print " + item.code);
            cb();
        }, 1200);
    }

    let requests = products.reduce((promiseChain, item) => {
        return promiseChain.then(() => new Promise((resolve) => {
            asyncFunction(item, resolve);
        }));
    }, Promise.resolve());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM