gpt4 book ai didi

javascript - 如何异步运行函数?

转载 作者:行者123 更新时间:2023-12-01 08:31:16 27 4
gpt4 key购买 nike

我有一个array

coords = [];

然后我运行这个函数

    getVirusData();

function getVirusData() {
getAvailableDatasets()
.then(combineDatasets)
.then(data => { // It's asynchronous
coords.push.apply(coords, data.map(item => item.Lat +"," + item.Long));
});
}

function getAvailableDatasets() {
return $.getJSON('https://api.github.com/repos/CSSEGISandData/COVID-19/contents/csse_covid_19_data/csse_covid_19_time_series')
.then((files) => {
return Promise.all(
files.filter(file => /^time_series_19-covid-.+\.csv$/.test(file.name))
.map(file => getDataset(file.download_url))
);
})
.catch(function(err) {
console.log(err);
})
}

function getDataset(url) {
return $.ajax(url)
.then(csv => {
const output = Papa.parse(csv, {
header: true, // Convert rows to Objects using headers as properties
dynamicTyping: true, // Convert some fields to Numbers automatically
});
if (output.data) {
const labelMatches = url.match(/time_series_19-covid-(.+)\.csv$/);
const label = labelMatches ? labelMatches[1] : "Untitled";

const formatted = output.data.map(area => {
const obj = {};

Object.keys(area).forEach(key => {
if (/^\d+\/\d+\/\d+$/.test(key)) {
obj[key] = { date: key, [label]: area[key] };
} else {
obj[key] = area[key];
}
});

return obj;
});



return formatted;
} else {
console.log(output.errors);
}
});
}

function combineDatasets(datasets) {
if (datasets.length) {
const combined = datasets.reduce((result, dataset, i) => {
if (i === 0) { return result; }
dataset.forEach(area => {
// Look for area with same coordinates
let existingArea = result.find(a => a.Lat === area.Lat && a.Long === area.Long);
if (!existingArea) {
result.push(area);
} else {
const dates = Object.keys(area).filter(key => /^\d+\/\d+\/\d+$/.test(key));
dates.forEach(date => existingArea[date] = Object.assign(area[date], existingArea[date]));
}
});
return result;
}, datasets[0]);

return combined.map(area => {
const obj = { data: [] };

Object.keys(area).forEach(key => {
if (/^\d+\/\d+\/\d+$/.test(key)) {
obj.data.push(area[key]);
} else {
obj[key] = area[key];
}
});

return obj;
});
} else {
throw "No datasets were found";
}
}

然后在将所有值插入数组后,我需要运行它

    drawMarkers();

function drawMarkers() {
for (var a = 0; a < coords.length; ++a) {
var pin = coords[a].split(',');
var latLng = new google.maps.LatLng(pin[0], pin[1]);
var marker = new google.maps.Marker({
position: latLng
});
}
}

当我运行时drawMarkers();我没有得到任何标记,如果我 console.log(pin) for loop之后我什么也没得到,因此一定有一个 asynchronous问题

更新完整代码

      (function($) {

var markers = [],
circle,
latitude = [],
longitude = [],
datesExternal = [],
links = [],
years = [],
type = [],
coords = [],
oggetti = [],
scuole = [],
privati = [],
markerCluster,
ids = [],
currentSite = [],
author = [],
site = [],
titles = [];

var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.600486, lng: 9.261252},
zoomControl: true,
zoom: 2,
minZoom: 2,
maxZoom: 18,
noClear: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
styles: [
{
"featureType": "administrative",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative",
"elementType": "geometry.fill",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "administrative",
"elementType": "geometry.stroke",
"stylers": [
{
"weight": "1.00"
},
{
"color": "#ffffff"
},
{
"visibility": "off"
}
]
},
{
"featureType": "administrative",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#484848"
}
]
},
{
"featureType": "administrative.country",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.country",
"elementType": "geometry.stroke",
"stylers": [
{
"visibility": "on"
}
]
},
{
"featureType": "administrative.country",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#484848"
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.province",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.province",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#484848"
}
]
},
{
"featureType": "administrative.locality",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.neighborhood",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "administrative.neighborhood",
"elementType": "labels.text.fill",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.land_parcel",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{
"color": "#e2e2e2"
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "landscape",
"elementType": "labels",
"stylers": [
{
"color": "#484848"
}
]
},
{
"featureType": "landscape.natural",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "landscape.natural",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#484848"
}
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road.local",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "transit",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "water",
"elementType": "all",
"stylers": [
{
"color": "#ededed"
}
]
}
],
draggable: true,
clickable: true,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
scrollwheel: false,
animatedZoom: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false
});


getVirusData();

function getVirusData() {
getAvailableDatasets()
.then(combineDatasets)
.then(data => { // It's asynchronous
coords.push.apply(coords, data.map(item => item.Lat + "," + item.Long));
}).then(function(entry) {
for (var a = 0; a < coords.length; a++) {
var pin = coords[a].split(',');
console.log(pin);
var latLng = new google.maps.LatLng(pin[0], pin[1]);
var marker = new google.maps.Marker({
position: latLng
});
}
});
}

function getAvailableDatasets() {
return $.getJSON('https://api.github.com/repos/CSSEGISandData/COVID-19/contents/csse_covid_19_data/csse_covid_19_time_series')
.then((files) => {
return Promise.all(
files.filter(file => /^time_series_19-covid-.+\.csv$/.test(file.name))
.map(file => getDataset(file.download_url))
);
})
.catch(function(err) {
console.log(err);
})
}

function getDataset(url) {
return $.ajax(url)
.then(csv => {
const output = Papa.parse(csv, {
header: true, // Convert rows to Objects using headers as properties
dynamicTyping: true, // Convert some fields to Numbers automatically
});
if (output.data) {
const labelMatches = url.match(/time_series_19-covid-(.+)\.csv$/);
const label = labelMatches ? labelMatches[1] : "Untitled";

const formatted = output.data.map(area => {
const obj = {};

Object.keys(area).forEach(key => {
if (/^\d+\/\d+\/\d+$/.test(key)) {
obj[key] = {
date: key,
[label]: area[key]
};
} else {
obj[key] = area[key];
}
});

return obj;
});



return formatted;
} else {
console.log(output.errors);
}
});
}

function combineDatasets(datasets) {
if (datasets.length) {
const combined = datasets.reduce((result, dataset, i) => {
if (i === 0) {
return result;
}
dataset.forEach(area => {
// Look for area with same coordinates
let existingArea = result.find(a => a.Lat === area.Lat && a.Long === area.Long);
if (!existingArea) {
result.push(area);
} else {
const dates = Object.keys(area).filter(key => /^\d+\/\d+\/\d+$/.test(key));
dates.forEach(date => existingArea[date] = Object.assign(area[date], existingArea[date]));
}
});
return result;
}, datasets[0]);

return combined.map(area => {
const obj = {
data: []
};

Object.keys(area).forEach(key => {
if (/^\d+\/\d+\/\d+$/.test(key)) {
obj.data.push(area[key]);
} else {
obj[key] = area[key];
}
});

return obj;
});
} else {
throw "No datasets were found";
}
}

最佳答案

您引用的脚本可能不正确。通过运行以下脚本检查控制台。还将您的 drawMarker 逻辑转移到调用的最后。

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

let coords = [];

getVirusData();

function getVirusData() {
getAvailableDatasets()
.then(combineDatasets)
.then(data => { // It's asynchronous
coords.push.apply(coords, data.map(item => item.Lat + "," + item.Long));
}).then(function(entry) {
for (var a = 0; a < coords.length; a++) {
var pin = coords[a].split(',');
console.log(pin);
var latLng = new google.maps.LatLng(pin[0], pin[1]);
var marker = new google.maps.Marker({
position: latLng
});
}
});
}

function getAvailableDatasets() {
return $.getJSON('https://api.github.com/repos/CSSEGISandData/COVID-19/contents/csse_covid_19_data/csse_covid_19_time_series')
.then((files) => {
return Promise.all(
files.filter(file => /^time_series_19-covid-.+\.csv$/.test(file.name))
.map(file => getDataset(file.download_url))
);
})
.catch(function(err) {
console.log(err);
})
}

function getDataset(url) {
return $.ajax(url)
.then(csv => {
const output = Papa.parse(csv, {
header: true, // Convert rows to Objects using headers as properties
dynamicTyping: true, // Convert some fields to Numbers automatically
});
if (output.data) {
const labelMatches = url.match(/time_series_19-covid-(.+)\.csv$/);
const label = labelMatches ? labelMatches[1] : "Untitled";

const formatted = output.data.map(area => {
const obj = {};

Object.keys(area).forEach(key => {
if (/^\d+\/\d+\/\d+$/.test(key)) {
obj[key] = {
date: key,
[label]: area[key]
};
} else {
obj[key] = area[key];
}
});

return obj;
});



return formatted;
} else {
console.log(output.errors);
}
});
}

function combineDatasets(datasets) {
if (datasets.length) {
const combined = datasets.reduce((result, dataset, i) => {
if (i === 0) {
return result;
}
dataset.forEach(area => {
// Look for area with same coordinates
let existingArea = result.find(a => a.Lat === area.Lat && a.Long === area.Long);
if (!existingArea) {
result.push(area);
} else {
const dates = Object.keys(area).filter(key => /^\d+\/\d+\/\d+$/.test(key));
dates.forEach(date => existingArea[date] = Object.assign(area[date], existingArea[date]));
}
});
return result;
}, datasets[0]);

return combined.map(area => {
const obj = {
data: []
};

Object.keys(area).forEach(key => {
if (/^\d+\/\d+\/\d+$/.test(key)) {
obj.data.push(area[key]);
} else {
obj[key] = area[key];
}
});

return obj;
});
} else {
throw "No datasets were found";
}
}
<script src="https://cdn.jsdelivr.net/npm/papaparse@5.1.1/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

关于javascript - 如何异步运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60584393/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com