JavaScript getter返回promise值

时间:2017-07-29 08:18:49

标签: javascript es6-promise

如何使 JavaScript 对象获取器返回promise的返回值?

请参阅下面的代码段,了解我想要实现的目标。



var my_object = {
    get latest() {
        return axios.get('https://jsonplaceholder.typicode.com/posts/1')
            .then(function (response) {
                return response.data;
            });
    }
};

console.log(my_object.latest); // Promise

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

尝试my_object.latest.then(x => console.log(x))

var my_object = {
	get latest() {
  	return axios.get('https://jsonplaceholder.typicode.com/posts/1').then(function (response) {
    	return response.data;
    });
	}
}

my_object.latest.then(x => console.log(x));
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>