node.jsasynchronousjestjsasync.jsfast-csv

how to correctly return data from async function node js, jest error


I have a function something like that:

async function example(){
let data = await another_function();
var ws = fs.createWriteStream('path');
let jsonData = [{'id':'1234', 'name': 'Alex'}];
    fastcsv
        .write(jsonData, { headers: true })
        .on("finish", function() {
            console.log('success');
        })
        .pipe(ws)
return true;
}

But when I run a test using jest I get an error:

Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "success".

Test function looks like this:

test('success', async() => {
        var expected = true;
        var result = await example();
        assert.equal(result, expected);
    })

How can I change example function to run it synchronously? And await till I get 'true' as return data from this function


Solution

  • Can you try refactoring your example function as follows.

    You can wait for that particular promise in function example() to be resolved. from the main function. In this case we are not returning a value from the function, but a promise that can be awaited and then the value can be used. You can wrap the function call under a try catch block and you can reject on error from example() and handle the error in the main function.

    function example(){
        // returning a promise()
    
        return new Promise(async(resolve, reject)=>{
            let data = await another_function();
            var ws = fs.createWriteStream('path');
            let jsonData = [{'id':'1234', 'name': 'Alex'}];
            fastcsv
            .write(jsonData, { headers: true })
            .on("finish", function() {
                console.log('success');
    
                // return in here, as the process ends here
                resolve(true);
    
                // stop function flow.
                return
            })
            .pipe(ws)
            
    
            // resolve() : on successfull execution
            // use reject(value) to move the execution to catch block on the main function
        })
    }