鍍金池/ 問答/HTML/ 初學(xué)es6,調(diào)用receiveData方式,雖然能讀取數(shù)據(jù),但是返回的data依

初學(xué)es6,調(diào)用receiveData方式,雖然能讀取數(shù)據(jù),但是返回的data依然是空

module.exports = {

    fetchData( dataUrl, start ) {
        return new Promise((resolve, reject) => {
            fetch(`${dataUrl}/data${(start+ 0 + '').padStart(2, '0')}.json`)
                .then((data) => {
                    resolve(data.json());
                }, (error) => {
                    reject(error);
                })
        });

    },

    async getData( dataUrl, start ) {

        const _self = this;
        let data = await _self.fetchData( dataUrl, start );
        return data;

    },
    
    receiveData( dataUrl, start ) {
        const _self = this;
        let data = {};

        _self.getData('virtual/result', 2).then(
            function(responseThenData) {
                data = responseThenData;
            })
            .then(function() {
                //console.log('abc')
            })
            .catch(function(e) {
                console.log("promise, error =", e);
            });
        
        return data;
    }


}

我希望返回的data 是讀取到的數(shù)據(jù),怎么修改啊?

回答
編輯回答
尐飯團(tuán)

你的getData是異步的,當(dāng)你調(diào)用receiveData的時(shí)候,會(huì)直接返回空的Data出來,因?yàn)槟愕膁ata賦值操作是在異步回調(diào)里面去做的,但是你的return卻不是在回調(diào)里面。你應(yīng)該把receiveData也弄成async,然后調(diào)用的時(shí)候用await

async receiveData( dataUrl, start ) {
        const _self = this;

        return _self.getData('virtual/result', 2)       
    }
    
let data = await receiveData() 
// 或者下面這樣
receiveData.then(
            function(responseThenData) {
                //responseThenData;
            })
            .then(function() {
                //console.log('abc')
            })
            .catch(function(e) {
                console.log("promise, error =", e);
            });    

大概是這么改

2018年5月22日 07:39
編輯回答
不歸路
receiveData( dataUrl, start ) {
        const _self = this;

        _self.getData('virtual/result', 2)
            .catch(function(e) {
                console.log("promise, error =", e);
            });
        
        
    }
    


const data = await receiveData();
console.log(data);
2017年10月9日 05:10