如何在nodejs中的另一个文件中获取嵌套回调结果?

时间:2017-06-30 16:45:43

标签: javascript node.js express callback

所以我的API代码在这个文件api.js

api.js

var express = require('express');
var Vimeo = require('vimeo').Vimeo;
var lib = new Vimeo('dfdfdfdfdfdfd', 'WDIt+kEVudfghjklkjhgfdfghjkjhgfMaG9X3Ml', 'jhjhjhjhjhjhgfg');

var app = express();

app.listen(9999);
var results =
    app.get('/api', function (req, res) {
        lib.request(/*options*/{
            // This is the path for the videos contained within the staff picks channels
            path: '/channels/staffpicks/videos',
            // This adds the parameters to request page two, and 10 items per page
            query: {
                page: 1,
                per_page: 2,
                fields: 'uri,name,description,duration,created_time,modified_time'
            }
        }, /*callback*/function (error, body, status_code, headers) {
            if (error) {
                // console.log('error -------------------------------------');
                // console.log(error);
            } else {
                console.log(body); //how to get this in server.js
                res.send(JSON.stringify(body['data'])); //how to get this in server.js

            }
        });

    });
console.log("Server is listening");
module.exports = {
    results: results,
}

server.js

var api = require('./vimeo/api.js');
var a  =  api.results;
//blah blah
 console.log(a);// how to get calback data from api.js function here?
 }));

如何访问api.js中可用的server.js中的console.log值?

3 个答案:

答案 0 :(得分:1)

app.get()来电包裹在这样的Promise中:

var results =
  new Promise(resolve => app.get('/api', function (req, res) {
    ...
  }));

然后将console.log(body);替换为:

resolve(body);

现在resultsPromise,因此一旦结算就会在server.js中提供:

var api = require('./vimeo/api.js');
api.results.then((a) => {
  console.log(a);
});

答案 1 :(得分:1)

假设api.jsserver.js都在同一个进程上运行,您可以向server.js添加一个函数,以拦截写入process.stdout的任何内容。一个可以调用钩子函数的函数,钩子函数需要返回写入process.stdout的原始参数,因此它不会中断console.log()

我如何使用它的一个例子是拦截记录到控制台的任何内容并将其写入文件。它不需要任何您希望截取console.log()的文件中的任何其他代码,它将适用于在同一进程上运行的process.stdout写入的任何内容。

function hookStdOut(hook => {
  process.stdout.write = (write => {
    return (...args) => {
      args[0] = hook[args[0]]
      write.apply(process.stdout, args)
    }
  })(process.stdout.write)
}

hookStdOut(chunk => {
  // access whatever was being written to stdout and process
  // you cannot use console.log within this function 
  // because it will result in an infinite loop since 
  //console.log writes to process.stdout

  // return the chunk so it will be written back to process.stdout
  return chunk
})

答案 2 :(得分:0)

您可以在server.js中导出一个函数,并在可用时立即从api.js传递异步数据。

server.js

var api = require('./vimeo/api.js');
module.exports = function(data){
  var a  =  api.results;
 console.log(data); //your async data

}

和api.js内部

//after you receive the data
else {
  var serverModule = require('./server');
  serverModule(data); //call the method
  res.send(JSON.stringify(body['data']));
}