如何从nodejs中的异步函数返回一个值?

时间:2017-03-16 19:07:10

标签: javascript node.js youtube node-modules

var fs = require('fs');
var ytdl = require('ytdl-core');

var favicon = require('serve-favicon');
var express = require('express');
var app = express();

app.use(favicon(__dirname + '/public/favicon.png'));
app.get('/:id',function (req,res){
	 ID = req.params.id;

var url = 'http://www.youtube.com/watch?v='+ID;

//function
  ytdl(url,
  function(err, format) {

    if (err) throw err;
    
       value =  format.formats;//this is the json objact from ytdl module
       return value;// i want return this value to user
       console.log(format.formats);//i am getting value... in console but not outside of the function..       
});

res.send(ytdl);//i want to send that async objact to this page....

});
app.listen(80);
 

所以我希望“异步函数”之外的“值变量”,如果不可能那么我想将json对象发送到浏览器,但我不知道如何发送,所以我被困在这里所以请建议我下一步应该做什么?

ps:我已经尝试过全局变量,但仍面临问题......

提前感谢...

1 个答案:

答案 0 :(得分:1)

您只需直接从回调中发送带有value的{​​{1}}变量:

res.send