Javascript 如何在运行另一个函数之前等待fetch完成

Javascript 如何在运行另一个函数之前等待fetch完成,javascript,async-await,fetch,Javascript,Async Await,Fetch,我目前正在尝试创建一个带有标记的地图,如果用户之前表示该标记是他们的“最爱”,我希望一些标记可以用不同的图标表示 为此,我尝试使用一个函数,首先获取数据,然后将部分数据推送到数组中,然后使用另一个函数创建地图并用标记填充它。我希望第二个函数只在第一个函数完成后运行。不幸的是,每次我运行代码时,所有的标记都是相同的,似乎应该包含所有常用站点ID的数组都是空的。我认为这意味着wait没有正常工作,因为第一个函数还没有完成运行 代码是: var favouriteStops = [] async f

我目前正在尝试创建一个带有标记的地图,如果用户之前表示该标记是他们的“最爱”,我希望一些标记可以用不同的图标表示

为此,我尝试使用一个函数,首先获取数据,然后将部分数据推送到数组中,然后使用另一个函数创建地图并用标记填充它。我希望第二个函数只在第一个函数完成后运行。不幸的是,每次我运行代码时,所有的标记都是相同的,似乎应该包含所有常用站点ID的数组都是空的。我认为这意味着wait没有正常工作,因为第一个函数还没有完成运行

代码是:

var favouriteStops = []

async function firstFunction(){
    fetch("api/favstop/")
    .then(response => {
        return response.json();
    })
    .then(data => {
    for(var i = 0; i<= data.length; i++){
        favouriteStops.push(data[i].stopid)
     }
 })
};


function addFavStop (){
        console.log(favouriteStops)
    }

async function initMap(){

    await firstFunction();
    //Map options
    var options = {
        zoom: 15,
        center: {lat:53.3477, lng:-6.2800},
        styles: mapStyle,
        disableDefaultUI: true
    }

    //Creating the map 
    var map = new google.maps.Map(document.getElementById('map'), options);


    //Add marker function
    function addMarker(stop){

        var coords = {lat: stop.lat, lng: stop.long}
        //Style for the icon
        if (favouriteStops.includes(stop.id)){
            var icon = {
                url: '../static/images/favourite.png',
                scaledSize: new google.maps.Size(12, 12)
            };
        } else {
            var icon = {
                url: '../static/images/bus-stop.png',
                scaledSize: new google.maps.Size(12, 12)
            };
            console.log(favouriteStops, stop.id)
        }

        var marker = new google.maps.Marker({
            position: coords,
            map:map,
            icon: icon,
            scaledSize: new google.maps.Size(1, 1),
            name:stop.name,
            id:stop.id
        })

        var infoWindow = new google.maps.InfoWindow({
            content: marker.name + '<br>' + '<button htmlType="submit" onClick=addFavStop()> Add Stop As Favourite </button>'
        });

        marker.addListener('click', function(){
            infoWindow.open(map, marker);
        });

    }

    //Adding markers for each stop
    for(var i = 0;i < stops_import.length;i++){
        addMarker(stops_import[i]);
    }
}
var-favoritestops=[]
异步函数firstFunction(){
获取(“api/favstop/”)
。然后(响应=>{
返回response.json();
})
。然后(数据=>{

对于(var i=0;ifor
wait
要实际等待
fetch
完成,您应该返回承诺:

async function firstFunction(){
  return fetch("api/favstop/")
  .then(response => {
    return response.json();
  })
  .then(data => {
    for(var i = 0; i<= data.length; i++){
      favouriteStops.push(data[i].stopid)
    }
  })
};
异步函数firstFunction(){ 返回fetch(“api/favstop/”) 。然后(响应=>{ 返回response.json(); }) 。然后(数据=>{
对于(var i=0;ifor
wait
要实际等待
fetch
完成,您应该返回承诺:

async function firstFunction(){
  return fetch("api/favstop/")
  .then(response => {
    return response.json();
  })
  .then(data => {
    for(var i = 0; i<= data.length; i++){
      favouriteStops.push(data[i].stopid)
    }
  })
};
异步函数firstFunction(){ 返回fetch(“api/favstop/”) 。然后(响应=>{ 返回response.json(); }) 。然后(数据=>{
对于(var i=0;i您可以通过使用
wait
内部
firstFunction
轻松解决此问题,如:

async function firstFunction() {
  const response = await fetch("api/favstop/")
  const data = await response.json();
  for (var i = 0; i <= data.length; i++) {
    favouriteStops.push(data[i].stopid)
  }
};
异步函数firstFunction(){ const response=wait fetch(“api/favstop/”) const data=wait response.json(); 对于(var i=0;i{ 返回response.json(); }) 。然后(数据=>{
对于(var i=0;i您可以通过使用
wait
内部
firstFunction
轻松解决此问题,如:

async function firstFunction() {
  const response = await fetch("api/favstop/")
  const data = await response.json();
  for (var i = 0; i <= data.length; i++) {
    favouriteStops.push(data[i].stopid)
  }
};
异步函数firstFunction(){ const response=wait fetch(“api/favstop/”) const data=wait response.json(); 对于(var i=0;i{ 返回response.json(); }) 。然后(数据=>{
对于(var i=0;i您不需要在异步函数中使用承诺链。事实上,它有点违背了整个目的。因此,您的异步函数看起来有点像:

async function firstFunction(){
   const fetcher = await fetch("api/favstop/");
   const data = await fetcher.json();
   
   for(var i = 0; i<= data.length; i++){
      favouriteStops.push(data[i].stopid)
   }
};
异步函数firstFunction(){ const fetcher=await fetch(“api/favstop/”); const data=await fetcher.json();
对于(var i=0;i您不需要在异步函数中使用承诺链。事实上,它有点违背了整个目的。因此,您的异步函数看起来有点像:

async function firstFunction(){
   const fetcher = await fetch("api/favstop/");
   const data = await fetcher.json();
   
   for(var i = 0; i<= data.length; i++){
      favouriteStops.push(data[i].stopid)
   }
};
异步函数firstFunction(){ const fetcher=await fetch(“api/favstop/”); const data=await fetcher.json();
对于(var i=0;i
async
函数需要返回一个承诺,因此只需在
firstFunction
中的
fetch
之前添加
return
,然后在
firstFunction
中的
fetch
之前添加
return
。当我将第一个函数更改为该函数时,我得到以下错误:“无法读取未定义的属性'stopid'”当我将第一个函数更改为此时,会出现以下错误:“无法读取未定义的属性'stopid'”。当我将第一个函数更改为此时,映射无法加载。在控制台中,我会收到一个错误,说明:“未捕获(承诺中)TypeError:无法读取未定义“”的属性“stopid”这是另一个问题。可能是因为数组中只有stopid,而没有整个stop项,但是您发布的代码没有告诉我们
stops\u import
实际上是什么。当我将第一个函数更改为该函数时,映射无法加载。在控制台中,我收到一个错误,说明:“Uncaught(in promise)”TypeError:无法读取未定义“”的属性“stopid”这是另一个问题。可能是因为数组中只有stopid,而没有完整的stop项,但是您发布的代码没有告诉我们
stops\u import
实际上是什么。不幸的是,这两种方法对我都不起作用。在这两种情况下,映射都无法加载。在控制台中,我收到一个错误,说明:“Uncaught(in promise)”TypeError:无法读取未定义的属性'stopid'。不幸的是,这两个属性对我都不起作用。在这两种情况下,映射都无法加载。在控制台中,我收到一个错误声明:“未捕获(承诺中)TypeError:无法读取未定义的属性'stopid'。