从功能中获取信息

时间:2016-08-19 16:05:50

标签: javascript node.js

如何从功能中获取信息?因为当我将文件启动到终端时,

console.log(latitude1 + " " + longitude1); 

返回“未定义”,而不是当我把

 console.log(latitude1 + " " + longitude1);

在函数中,返回longitue和纬度。

var triangulate = require('wifi-triangulate')

var latitude1;
var longitude1;

triangulate(function (err, location) {
  //if (err) throw err
  var latitude = location.lat;
  var longitude = location.lng;
  latitude1 = latitude;
  longitude1 = longitude;
});
  console.log(latitude1 + " " + longitude1); 

2 个答案:

答案 0 :(得分:1)

您不能只运行异步(非阻塞)功能,并在功能检查结果后。

因为当triangulate函数完成并转到下一行时,JS不会等待(不会阻止执行)。

对于新手,我会说它在jquery中类似于ajax调用。

检查此示例:

var async = require('async');
var triangulate = require('wifi-triangulate');

function doSomethingWithLocation(location, cb) {
  console.log(location);
  // save to db and etc operations here
  cb();
}

async.waterfall([
  triangulate,
  doSomethingWithLocation
]);

console.log('Here goes triangulate result:'); // while `triangulate` will work, it will output message before that triangulate will pass result to `doSomethingWithLocation`



如果您想连续获取位置数据并对其进行操作,请查看此示例:

1)我们创建一个名为location的组件,并将所需的功能放在其中

部件/ location.js:

var triangulate = require('wifi-triangulate');

module.exports = function(callback) {
  triangulate(function(err, location) {
    if(err) {
      console.error(err);
      return callback({});
    }

    callback(location);
  });
}

2)在app文件中,我们需要这个组件并使用它 app.js:

var async = require('async');
var getLocation = require('./components/location');

var latitude, longitude;

function handleLocation(lat, lon) {
  console.log('Got location information:', lat, lon);

  // You can add here db query to update/insert info to db
}


getLocation(function(data) {
  latitude = data.lat;
  longitude = data.lng;
  handleLocation(latitude, longitude);
});

console.log('You cannot see lat, lon', latitude, longitude);
console.log('Because You\'ve to wait for execution of getLocation to complete');

答案 1 :(得分:1)

用回调样式编写的

triangulate包,可以将其转换为异步,或者按原样使用

回调

var triangulate = require('wifi-triangulate')

function myTriangulate(callback) {
  triangulate(function (err, location) {
    if (err) throw err;
    callback(location);
  });
}

myTriangulate(function(loc) {
  console.log(loc.latitude + " " + loc.longitude); 
});

异步

var triangulate = require('wifi-triangulate')
//use default node's promise lib
//or similar libs like bluebird

function myTriangulate() {
  return new Promise(function(resolve, reject) {
    triangulate(function (err, location) {
      if (err) return reject(err);
      resolve(location);
    });
  }); 
}

myTriangulate().then(function(loc) {
  console.log(loc.latitude + " " + loc.longitude); 
});