如何从nodejs中的异步函数中获取return一个值?

how to get return a value from asynchronous function in nodejs?

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

所以我希望 "value variable" 在 "async function" 之外,如果不可能,那么我想将 json 对象发送到浏览器,但我不知道如何发送那个,所以我被困在这里所以请建议我下一步该怎么做?

ps: 我已经尝试过作为全局变量但仍然遇到问题..

提前致谢...

您只需直接从回调中发送带有 res.sendvalue 变量:

ytdl(url, function(err, format) {
  if (err) throw err;
  var value = format.formats;
  res.send(value);
});