Search code examples
node.jses6-promise

How should you access the stack trace returned in the array of objects from Promise.allSettled() in addition to the error message?


Promise.allSettled() returns an array of objects with statuses fulfilled or rejected and the reason, eg: '[{status: 'rejected', reason: 'Error: some error message}, ...]'

If you console.log the error out you can see both the reason and the stack trace. However when you save output to a log file you simply see the reason and not the full stack trace. How do you also save the stack trace?


Solution

  • Reason gives you the error message. For full stack trace use reason.stack as below. The example here is batching a large number of promises so as not to run out of memory, with the stack trace also saved:

    const fs = require('fs');
    
    const batch = async myArr => {
        const res = [];
    
        for (let i = 0; i < myArr.length; i += 2) {
            const requests = myArr.slice(i, i + 2).map(num => {
                if (num % 2 === 0) {
                    return Promise.resolve(num);
                }
    
                if (num % 2 === 1) {
                    return Promise.reject(Error(`Rejected promise in for loop at num ${ num }`));
                }
            });
    
            // eslint-disable-next-line no-await-in-loop
            await Promise.allSettled(requests)
                .then(response => res.push(response));
        }
    
        return res.flat();
    };
    
    batch([1, 2, 3, 4, 5, 6])
        .then(res => {
            let failed = [];
    
            failed = res.filter(re => (re.status === 'rejected'));
    
            for (let i = 0; i < failed.length; i += 1) {
                fs.appendFileSync('reasons.txt', `${ failed[i].reason }\n`);
                fs.appendFileSync('stack-traces.txt', `${ failed[i].reason.stack }\n`);
            }
        });