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

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

问题描述

我试图创建一个返回对象,回调的信息的功能:

  VAR geoloc;VAR成功=功能(位置){
    geoloc = {
        经度:position.coords.longitude,
        纬度:position.coords.latitude
    };
};VAR的getLocation =功能(){
    navigator.geolocation.getCurrentPosition(成功,函数(){
        警报(失败);
    });    返回geoloc;
};

我怎样才能做到这一点?功能的getLocation 返回空值成功执行

谢谢!


解决方案

回调的使用,因为该功能是异步的

。回调在未来的某一时刻运行。

因此​​,回调之前是的getLocation 的回报被触发。这就是异步方法是如何工作的。

您不能等待回调,这不是它的工作原理。您可以在回调中添加的getLocation ,一旦它的完成运行。

  VAR的getLocation =函数(回调){
    navigator.geolocation.getCurrentPosition(功能(POS){
        succesfull(POS)
        typeof运算回调==='功能'和;&安培;回调(geoloc);
    },函数(){
        警报(失败);
    });
};

现在的而不是做 VAR X =的getLocation()并期待一个返回值,你怎么称呼它是这样的:

 的getLocation(功能(POS){
    的console.log(pos.longitude,pos.latitude);
});

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;
};

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

Thanks!

解决方案

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

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

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");
    });
};

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天全站免登陆