JavaScript doesn't seem to wait for return values

后端 未结 4 1330
我寻月下人不归
我寻月下人不归 2020-12-29 20:28

I\'ve been struggling with this for a while now. I\'m new to Javascript, and have been under the impression that the code I\'ve been writing has been running asynchronously.

4条回答
  •  萌比男神i
    2020-12-29 21:15

    Indeed, you are correct in realizing that the calls are asynchronous, and you are not getting a proper return value.

    Normally, when functions are called in js, they are synchronous.

    e.g. a() calls b(), and a() waits until b() to finish before continuing.
    

    However, in certain situations, such as making ajax or jsonp calls, it is done asynchronously. This is precisely what is happening when you call geocode().

    Your execution:

    initialize() is called;
    initialize() calls geocoder();
    geocoder makes a request to Google, and returns null in the meantime.
    initialze() calls makemap()
    the Google geocoder returns at some point, and executed the success callback, which you have defined as "return results;", but there is nothing to return, since the function has already ended.
    

    So, specifically, utilise the callback that is already built into the geocoder call:

    if (status == google.maps.GeocoderStatus.OK) {
        makeMap(results);
    }
    

提交回复
热议问题