debug-js / debug

A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers
MIT License
11.12k stars 932 forks source link

How to use debug.js with `Promise.all` #928

Closed fyc09 closed 1 year ago

fyc09 commented 1 year ago
const logger = require('debug')('test');

function sleep(second) {
        return new Promise((resolve, reject) => {
                setTimeout(resolve, second * 1000);
        });
}

async function test(id) {
        await sleep(Math.random());
        logger('first %o', id);
        await sleep(Math.random());
        logger('second %o', id);
}

async function run() {
        const ids = [1, 2, 3];
        Promise.all(ids.map(id => test(id)));
}

run();
$ DEBUG=* node test.js
  test first 1 +0ms
  test first 2 +570ms
  test first 3 +146ms
  test second 1 +136ms
  test second 2 +175ms
  test second 3 +609ms
$ DEBUG=* node test.js
  test first 1 +0ms
  test first 3 +154ms
  test second 1 +122ms
  test first 2 +369ms
  test second 3 +97ms
  test second 2 +883ms
$ DEBUG=* node test.js
  test first 3 +0ms
  test first 1 +654ms
  test second 3 +104ms
  test first 2 +27ms
  test second 2 +463ms
  test second 1 +82ms

The logs for each Promise in Promise.log are interleaved. Can I separate them, for example, and print all the logs together after each promise ends. I hope the result is like this:

  test first 3
  test second 3
  test first 1
  test second 1
  test first 2
  test second 2
Qix- commented 1 year ago

No there's no way to do that, sorry.