获取位于回调函数内的变量

时间:2017-03-29 17:58:33

标签: javascript node.js express

var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}
exports.parse = function(){
   request(options, callback);
}

嗨,我怎样才能在info函数中找到callback变量。 对不起,我是js的初学者,并没有在我的大脑/和平中找到答案

3 个答案:

答案 0 :(得分:2)

回调函数用于处理非阻塞 - 异步性质。当作业阻止I / O时,它只是将其放入任务队列并向前移动。完成任务后,是时候触发回调函数了,我们可以以任何我们想要的方式处理这些返回值。这是回调函数的使用。您可以阅读有关事件循环的信息,以便更好地理解。

在这里,你必须传递自定义回调函数才能正确处理场景。

var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

exports.parse = function(cb){
   request(options, cb);
}

在你想要使用解析方法的地方使用像这样..

parse(function(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");

// TODO with info

  }
});

答案 1 :(得分:0)

在更高的范围内声明变量将使其可访问。在调用回调之前,不会更新较高范围中的值。

//This line is required to turn off all autosizing/positioning
View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();

// Get the screen dimensions and the middle of the screen 
// for button positioning

var barheight = this.NavigationController.NavigationBar.Bounds.Height; 
// Height of the navigation bar

var height = UIScreen.MainScreen.Bounds.Height; 
var width = UIScreen.MainScreen.Bounds.Width;
int middle = (int) UIScreen.MainScreen.Bounds.Width / 2;  
// We cast to int to truncate float, 
// int will convert implictly to float when used (Visual Studio).


var heightavailabletoimageviw = height -74 - 47 - 26 - 60; 
// 74 is the height of the banner, 47 is the height of the buttons and 
// 26 is the height of the title label plus a 5px gap  The rest of the 
// screen is available for use by the image view, 
// set heightavailabletoimageviw to this value
// Had to subtract 60 because the image view still overlapped 
// the buttons, no idea why.  Anyone?

// Had to add a constraint to the imageview because if I didn't
// it automatically scaled to the size of the image, not good.
ThePhoto.AddConstraints(
    ThePhoto.Width().EqualTo(UIScreen.MainScreen.Bounds.Width),
    ThePhoto.Height().EqualTo(heightavailabletoimageviw) 
);

// Had to fix the size of the imagebutton otherwise the button size
// scaled to the size of the image
btnPhoto.AddConstraints(
    btnPhoto.Width().EqualTo(62f),
    btnPhoto.Height().EqualTo(47f)
);

// Now we add the constraints to the viewcontroller to finish up.
View.AddConstraints(

    // Can't cover the navigation bar (unless it isn't there, mine is), 
    // this value sets all other relative positions    
    Banner.AtTopOf(View, barheight), 
    Banner.AtRightOf(View, 0),
    Banner.AtLeftOf(View, 0),

    lblTitle.Below(Banner, 0),
    lblTitle.WithSameWidth(Banner),

    ThePhoto.Below(lblTitle, 5), 
    ThePhoto.WithSameWidth(lblTitle),

    // I have no idea why, but I had to use negative
    // values for the buttons to appear on the screen,
    // otherwise they were off screen.
    // If anyone could explain this, I would appreciate it.
    btnUpload.AtBottomOf(View),
    btnUpload.ToLeftOf(View,-60),

    // Same here, had to use negative values for button to
    // position correctly on the screen
    btnPhoto.AtBottomOf(View), 
    btnPhoto.ToLeftOf(View,-(middle + 31)),

   // Again, same thing.
   btnMainMenu.AtBottomOf(View),
   btnMainMenu.ToRightOf(View,-80)

);

答案 2 :(得分:0)

如果您的目标只是解析您的身体并轻松获得解析的JSON,那么您应该考虑使用诸如body-parser之类的中间件。这是一种标准模式......例如,考虑以下代码:(来自https://github.com/expressjs/body-parser

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})