我正在使用MapBox和React,并且试图了解为什么这些代码以不同的顺序运行...
1)我创建了一个单独的函数,从componentDidMount调用,代码逐行运行(我依次获得控制台日志:1、2、3、4、5、6、7)
componentDidMount() {
console.log(1);
let mapOptions = {
container: this.mapContainer,
style: 'mapbox://styles/mapbox/streets-v11',
center: [this.state.lng, this.state.lat],
zoom: this.state.zoom
}
console.log(2);
if( "geolocation" in navigator){
console.log(3);
navigator.geolocation.getCurrentPosition((position) => {
console.log(4);
const { longitude, latitude } = position.coords
const coordinates = [longitude,latitude]
console.log(5);
mapOptions.center = coordinates
console.log(6);
this.createMap(mapOptions)
})
}
}
createMap(mapOptions){
console.log(7);
const map = new mapboxgl.Map(mapOptions);
}
2)我在componentDidMount中调用createMap函数,并使该函数中的所有代码和代码以不同的顺序运行:1,2,3,7,4,5,6
componentDidMount() {
this.createMap()
}
createMap(){
console.log(1);
let mapOptions = {
container: this.mapContainer,
style: 'mapbox://styles/mapbox/streets-v11',
center: [this.state.lng, this.state.lat],
zoom: this.state.zoom
}
console.log(2);
if( "geolocation" in navigator){
console.log(3);
navigator.geolocation.getCurrentPosition((position) => {
console.log(4);
const { longitude, latitude } = position.coords
const coordinates = [longitude,latitude]
console.log(5);
mapOptions.center = coordinates
console.log(6);
})
}
console.log(7);
const map = new mapboxgl.Map(mapOptions);
}
答案 0 :(得分:3)
这是因为navigator.geolocation.getCurrentPosition
是异步调用。
1。代码段1:
从已解决的Prom内部调用的控制台日志,从4到7。
2。代码段2
方法navigator.geolocation.getCurrentPosition
返回Promise,一切按原样继续。因此,您看到console.log(7)
首先运行。一旦诺言解决,其余的代码就会运行。
希望有帮助。