如何在nodejs中将参数从一个异步函数传递给另一个异步函数?

时间:2015-10-30 07:16:32

标签: javascript node.js asynchronous

这是代码,



var WebPageTest = require('webpagetest');
var wpt = new WebPageTest('url of the server');
var request = require('request');
var data_url;
var http = require('http');
var fs = require('fs');
var test_id;
var step = require('step');
step(
wpt.runTest('http://google.com', function(err, data) {
    console.log(err || data); 
    console.log('---------------');
    console.log('inside wptruntest function');
    console.log('----------------');
    data_url=data.data.summaryCSV; 
    test_id=data.data.testId;
    console.log(data_url);
    console.log('---------------');
    console.log(test_id);
    console.log('---------------');

    
}),


request(data_url, function (error, response, body) { 
       if (error) { 
      console.log(error); 
      } 
      console.log('inside request MODULE');
        console.log('---------------');
      console.log(body); 
      var data = body;
    })
);




我想在我的下一个异步函数中使用data_url的值,即请求,以便我可以从该url获取结果,此外我需要同步运行这两个函数,控制台的错误是:' undefined不是有效的uri或选项对象'

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

您必须使用async.waterfall,如下所示:

var async = reqquire('async');
    async.waterfall([
        function(callback) {
            callback(null, 'one', 'two');
        },
        function(arg1, arg2, callback) {
          // arg1 now equals 'one' and arg2 now equals 'two'
            callback(null, 'three');
        },
        function(arg1, callback) {
            // arg1 now equals 'three'
            callback(null, 'done');
        }
    ], function (err, result) {
        // result now equals 'done'
    });