函数调用在有机会设置重要数据之前被传递 [英] function call is passed over before having the chance to set important data

查看:116
本文介绍了函数调用在有机会设置重要数据之前被传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个功能在node.js获取外部IP从 https://icanhazip.com/ (方便的网站,检查出来) ,但是当调用该请求时,不允许在调用 return 之前完成该请求。这里是代码:

So I have this function in node.js that gets the external IP by grabbing it from https://icanhazip.com/ (handy website, check it out), but when the request is called it isn't allowed to finish before return is called. Here is the code:

var request = require('request');
var get_ext_ip = function(){
    var _ip; //Initialize a return variable

    //Launch an HTTPS request to a simple service that shows IP of client
    //The callback function isn't allowed to finish.
    request('https://icanhazip.com', function(error, response, body){
        _ip = body; //when finished store the response in the variable that is going to be returned.
    });

    //Return
    return _ip;
}

var ip = get_ext_ip();
console.log(ip); //undefined

所以我想,这里的问题是:如何让这个脚本等待回调函数在返回值之前完成

So I guess, the question here is: how do I make this script wait for that callback function to finish before returning a value?

推荐答案

这是因为Node中I / O请求的异步性质: get_ext_ip 在请求完成之前返回。

That's because of the asynchronous nature of I/O requests in Node: the function get_ext_ip returns before the request has finished.

处理此问题的一种方法是传递一个回调函数将在请求完成时被调用:

One of the methods of handling this is to pass a callback function which will get called when the request is done:

var request = require('request');
var get_ext_ip = function(callback) {
  request('https://icanhazip.com', function(error, response, body) {
    callback(error, body);
  });
}

get_ext_ip(function(err, ip) {
  if (err)
    console.log('an error occurred:', error);
  else
    console.log(ip);
});

这篇关于函数调用在有机会设置重要数据之前被传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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