gpt4 book ai didi

javascript - 为什么函数 in then 没有接收到对象

转载 作者:行者123 更新时间:2023-12-05 03:30:38 25 4
gpt4 key购买 nike

我理解 Promises 的概念,但有些事情对我来说似乎并不完全清楚。

我有以下 html:

<!DOCTYPE html> .......
<div id="map"></div>
<script
src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API&callback=initialize"
async></script>
</body>
</html>

<script src="js/currentRoute.js"></script>

我有以下 JS 代码:

async function getCurrentUserCoordinates() {
console.log("Am getCurrentUserCoordinates")

const url = baseUrl + `/SOME_REST_API_URL`;

if (checkAdminOrTechRights(parseToken(getToken()))) {
await fetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${getToken()}`
},
})
.then((response) =>
response
.json()
)
.then(terminals => {
let locations = [];
terminals.forEach(terminal => {
locations.push({
lat: terminal.latitude,
lng: terminal.longitude,
name: terminal.name,
location: terminal.location
})
})
console.log(locations) // ALL IS PRINTING OK HERE
return locations;
}).catch((err) => {
console.error(err);
})
}
}

function initMap(locations) {
console.log("Am initMap")
console.log("printing locations: " + locations) // I HAVE UNDEFINED HERE
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: {lat: 0.123123123123, lng: 0.123123123123},
});
const infoWindow = new google.maps.InfoWindow({
content: "",
disableAutoPan: true,
});

const markers = locations.map((terminal, i) => {
const label = `${terminal.name}, ${terminal.location}`;
const marker = new google.maps.Marker({
position: terminal,
label,
});

marker.addListener("click", () => {
infoWindow.setContent(label);
infoWindow.open(map, marker);
});
return marker;
});

new markerClusterer.MarkerClusterer({markers, map});
}


async function initialize() {
console.log("Am initialize")
getCurrentUserCoordinates()
.then(locations => initMap(locations))
.then(() => console.log("Am done"))
.catch((err) => {
console.error("ERROR!!! " + err);
})
}

我有以下日志:

Am initialize

currentRoute.js:2 Am getCurrentUserCoordinates

currentRoute.js:28 (26) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]0: {lat: 1.123123123, lng: 1.123123123, name: 'TERM-0001', location: 'LOCATION'}1: {lat: 1.123123123, lng: 1.123123123, name: 'TERM-0099', location: 'LOCATION'}2: ............ 25: {lat: 1.123123123, lng: 1.123123123, name: 'TERM-0023', location: 'LOCATION'}length: 26[[Prototype]]: Array(0)

currentRoute.js:37 Am initMap

currentRoute.js:38 printing locations: undefined

所以在我看来,当 getCurrentUserCoordinates() 返回结果(位置)时,必须调用 initMap()。在函数内部正在获取位置,并且在打印的日志中可以看到。但是位置在 initMap 函数中作为未定义传递。

我没有得到什么?

谢谢。

最佳答案

您的代码的主要问题是您从 then 中的嵌套函数内部调用 return,您认为它会从外部方法 getCurrentUserCoordinates 返回 但事实并非如此。

如果不将 async/await 与 then 混合使用,可以极大地简化您的功能 - 前者更易于管理。该代码还受益于将笨重的数组 + forEach 替换为数组上的简单 map

async function getCurrentUserCoordinates() {
console.log("Am getCurrentUserCoordinates")

const url = baseUrl + `/SOME_REST_API_URL`;

if (checkAdminOrTechRights(parseToken(getToken()))) {
try{
const result = await fetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${getToken()}`
},
});
const terminals = await result.json();
let locations = terminals.map( terminal => ({
lat: terminal.latitude,
lng: terminal.longitude,
name: terminal.name,
location: terminal.location
}))
console.log(locations) // ALL IS PRINTING OK HERE
return locations;
}
catch(err){
console.error(err);
}
}
}

* 请注意,此代码中的返回位置现在位于方法本身的外部范围内,但是由于该方法是async,它实际上返回一个Promise 所以你必须稍后等待它(见下文)。 H/T @JeremyThille

稍后在您的代码中也是如此

async function initialize() {
console.log("Am initialize")
try{
const currentUserCoords = await getCurrentUserCoordinates();
const locations = initMap(currentUserCoords);
console.log("Am done"))
}
catch(err){
console.error("ERROR!!! " + err);
}
}

关于javascript - 为什么函数 in then 没有接收到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70784285/

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