在javascript中等待回调 [英] Wait for callback in javascript

查看:51
本文介绍了在javascript中等待回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数返回一个带有回调信息的对象:

I'm trying to create a function that returns a object with information of a callback:

var geoloc;

var successful = function (position) {
    geoloc = {
        longitude: position.coords.longitude,
        latitude: position.coords.latitude
    };
};

var getLocation = function () {
    navigator.geolocation.getCurrentPosition(successful, function () {
        alert("fail");
    });

    return geoloc;
};

我该怎么做?函数 getLocationsuccessful 执行前返回空值.

How can I do this? The function getLocation return null value before successful is executed.

谢谢!

推荐答案

使用回调是因为函数是异步的.回调会在未来的某个时间点运行.

Callbacks are used because the function is asynchronous. The callback runs at some point in the future.

所以,是的 getLocation 在回调被触发之前返回.这就是异步方法的工作原理.

So, yes getLocation returns before the callback is triggered. That's how asynchronous methods work.

你不能等待回调,这不是它的工作方式.您可以向 getLocation 添加回调,该回调在完成后运行.

You cannot wait for the callback, that's not how it works. You can add a callback to getLocation, that runs once it's done.

var getLocation = function(callback){
    navigator.geolocation.getCurrentPosition(function(pos){
        succesfull(pos);
        typeof callback === 'function' && callback(geoloc);
    }, function(){
        alert("fail");
    });
};

现在不是执行 var x = getLocation() 并期望返回值,您可以这样调用它:

Now instead of doing var x = getLocation() and expecting a return value, you call it like this:

getLocation(function(pos){
    console.log(pos.longitude, pos.latitude);
});

这篇关于在javascript中等待回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆