简体   繁体   中英

How to return Promise from an async class function JavaScript

I am trying to unit test a code I re-wrote using promises. The class FileFactory has the following async function:

    async getFileHandler(filePath) {
    var self = this;
    for(const item of self.privateFileHandlers) {
        await item.canHandle(filePath)
        .then(function(response) {
            console.log("Response:",JSON.stringify(response));  //line A
            return response;
        }, function(error) {
            return error;
            //ignore since most handlers won't be able to handle.
            //also, the callback after the loop will inform that no filehandler was found.                
        })
        .catch(function(err){
            //console.log('Catching: ',JSON.stringify(err));
            return err;
            //ignore since most handlers won't be able to handle.
            //also, the callback after the loop will inform that no filehandler was found.
        });
    }
}

The response I am logging on line A contains what I would expect.

However, in my unit test, I don't get the response object.

        it('should return correct FileHandler child instance', function(){  
        var ff = new FileFactory();
        ff.getFileHandler("./tests/H1_20180528.csv").then(function(value) {console.log("Success",JSON.stringify(value));}).catch(function(err) {console.log("Fail",JSON.stringify(err));});
        //ff.getFileHandler("./tests/H1_20180528.csv").then(value => console.log("Success",JSON.stringify(value)));
        //console.log(JSON.stringify(fh));
    });

What am I missing here? Thank you.

This works:

async getFileHandler(filePath) {
    var self = this;
    for(const item of self.privateFileHandlers) {
        try {
            let response = await item.canHandle(filePath);
            if(response.status === "success")
                return response;
        } catch(e) {
            //ignore so it does not return on failed canHandle calls.
        }
    }
    throw 'No supporting file handler available.';
}

//the updated unit test

describe('Select handler', function () {
    it('should fail and return no file handler.', function () {
        var ff = new FileFactory();
        ff.getFileHandler("./tests/H1_20180528_fail2.csv")
        .then(function (value) {
            chai.assert(value.status === null);
        })
        .catch(function (err) {
            chai.assert(err !== null);
        });
    });

    it('should return correct FileHandler child instance', function () {
        var ff = new FileFactory();
        ff.getFileHandler("./tests/H1_20180528.csv")
        .then(function (value) {
            chai.assert(value.status === 'success');
        })
        .catch(function (err) {
            chai.assert(err === null);
        });
    });      
});

Change the inner body of your function to this:

try {
   let response = await item.canHandle(filePath);
   console.log("Response:", JSON.stringify(response)); // line A
   return response;
} catch (err) {
   return err;
}

If you're await ing a function within an async function you don't have to use then or catch .

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