87,964
社区成员
发帖
与我相关
我的任务
分享
<text>{{= fnGetNameFromCoords(value.location) }}</text> //调用方法根据坐标获得地名
function fnGetNameFromCoords(coord) {
var coords = coord.split(",")
var name = '';
map.getNameFromCoords({ //异步
lon: coords[0],
lat: coords[1]
},function(ret,err){
if(ret.status){
name = ret.sematicDescriptio //name还没得及赋值
}
});
return name; //先执行到这里,name = ''
}
function fnGetNameFromCoords(coord) {
var coords = coord.split(",");
return new Promise((resolve,reject) => {
map.getNameFromCoords({
lon: coords[0],
lat: coords[1]
}, function(ret,err){
if(ret.status){
resolve(ret.sematicDescription)
} else {
reject(new Error('没有数据'));
}
});
})
}
// 使 doT 模板支持 await
function asyncDoT(strTmpl, args) {
let global = function(){ return this; }();
let F = global.Function;
global.Function = (async function(){}).constructor;
let tmpl = doT.compile(strTmpl);
global.Function = F;
return tmpl(args);
}
async function render() {
let tmpl = ` {{~it:value:index}} <text>{{= await fnGetNameFromCoords(value.location) }}</text> {{~}}`;
let data = [ {location:'1,2'},{location:'3,4'} ];
document.body.innerHTML = await asyncDoT(tmpl, data); // 渲染时也要 await
}
render();
async function fnGetNameFromCoords(coord) {
var coords = coord.split(",")
var name;
var promise = new Promise(resolve => {
map.getNameFromCoords({
lon: coords[0],
lat: coords[1]
},function(ret,err){
if(ret.status){
name = ret.sematicDescription
resolve(name)
}
});
})
await promise;
return name;
}
、
渲染的部分:<text style="font-size: 1.3rem;color:gray">{{=fnGetNameFromCoords(value.location)}}</text>
却显示[object Promise],