簡體   English   中英

如何從異步類函數 JavaScript 返回 Promise

[英]How to return Promise from an async class function JavaScript

我正在嘗試對我使用 Promise 重新編寫的代碼進行單元測試。 FileFactory 類具有以下異步功能:

    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.
        });
    }
}

我在 A 行上登錄的響應包含我所期望的。

但是,在我的單元測試中,我沒有得到響應對象。

        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));
    });

我在這里缺少什么? 謝謝你。

這有效:

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.';
}

//更新的單元測試

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);
        });
    });      
});

將函數的內部主體更改為:

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

如果您正在await async函數中的函數,則不必使用thencatch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM