这似乎应该是微不足道的,但我已经追赶了三个星期。
我想从我的API中获取数据,并将其显示在从NativeScript.org Playground天气示例借来的Vue模板中。
而且,我希望使用ASYNC / AWAit,因为它看起来更优雅。
<template>
<Page class="Page" actionBarHidden="true" backgroundSpanUnderStatusBar="true">
<StackLayout>
<StackLayout row="0">
<Image class="event-image" :src="eventImage" />
<Label class="bold" :text="exported_event0" backgroundColor="gray"></Label>
<Label class="bold" :text="created_event1" backgroundColor="gray"></Label>
<Label class="bold" :text="created_event2" backgroundColor="gray"></Label>
</StackLayout>
</StackLayout>
</Page>
</template>
<script>
const httpModule = require("http");
var exported_event0;
var exported_event1;
var exported_event2;
var created_event1;
var created_event2;
var fetched_event;
export default {
data() {
return {
exported_event0: "A string of a returned event",
exported_event1: created_event1,
exported_event2: created_event2,
};
},
created() {
this.eventImage = "~/images/augustus.jpg";
this.created_event1 = "A stringy created event";
this.created_event2 = getEvent().then(result => console.log(result));
console.log("created_event2 is:" + this.created_event2);
},
};
async function getEvent() {
console.log("-----httpmodule ----------------------------");
let fetched_event = await httpModule.getJSON("https://agile-brushlands-36817.herokuapp.com/events/4.json").then(function(result) {
console.log("---------Event api fetched." + JSON.stringify(result));
}, function(error) {
console.error("the GETJSON eror" + JSON.stringify(error));
});
console.log("---------Event api fetched." + JSON.stringify(fetched_event));
return fetched_event;
};
</script>
1)可以/应该出口|数据(从模板)创建的方法是否可以简化?
2)如何使getEvent()调用等待数据获取?
这是(缩写)日志:
'-----httpmodule ----------------------------'
'---------Event api fetched.{"id":4,"title":"The armies of Richard I and Saladin fight it out in the Holy Land. Richard gets Arsuf; Saladin keeps Jerusalem.","year":1191,"position":null,"wikip":"http://en.wikipedia.org/wiki/Saladin#Third_Crusade","image":"","created_at":"2019-01-29T16:48:02.248Z","updated_at":"2019-01-29T16:48:02.248Z","url":"https://agile-brushlands-36817.herokuapp.com/events/4.json"}'
'---------Event api fetched.undefined'
CONSOLE LOG undefined
答案 0 :(得分:1)
使用async/await
时,您不需要使用诺言。您可以更新getData函数以正确使用await并返回结果
async function getEvent() {
try{
console.log("-----httpmodule ----------------------------");
let result = await httpModule.getJSON("https://agile-brushlands-36817.herokuapp.com/events/4.json");
console.log("---------Event api fetched." + JSON.stringify(result));
return result;
}
catch(error){
console.error("the GETJSON eror" + JSON.stringify(error));
}
}
然后,您将要确保您的created
钩子也是异步的,因此您可以在调用getData
时在其中使用await关键字
async created() {
this.eventImage = "~/images/augustus.jpg";
this.created_event1 = "A stringy created event";
this.created_event2 = await getEvent();
console.log("created_event2 is:" + this.created_event2);
},