0

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

1 Answer 1

1

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
    })
}
Sign up to request clarification or add additional context in comments.

4 Comments

Jest throw another error in this case: thrown: "Exceeded timeout of 5000 ms for a test." If I get it right, test function didn't get any value from 'example' function
Is your "end" listner working ? Can you try the following edit
Now it works! Thanks a lot! Can you explain what for we are using 'return'? is it necessary?
Actually some times the resolve will be triggered, and the function execution might continue, thus returning it will make sure it ends the function execution. Also if you found the answer helpful make sure you mark it as accepted, as it might help other people with the same problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.