2017-06-18 66 views
1

我試圖在我的lambda函數中設置順序異步調用。我爲此使用標準異步庫,並沒有成功運行所有控制檯打印。在Lambda中使用異步

// async import 
var async = require('async'); 

exports.handler = (event, context, callback) => { 

    async.waterfall([ 
     function func1(){ 
      console.log('1'); 
     }, 
     function func2(){ 
      console.log('2'); 
     }, 
     function func3(){ 
      console.log('3'); 
     }, 
    ], function (error, success) { 
     if (error) { console.log('Something is wrong!'); } 
     callback(null, 'success'); 
    }); 
}; 

我看到的是:

START RequestId: b9dc249e-53ce-11e7-923a-95d7e896a384 Version: $LATEST 
2017-06-18T02:35:00.915Z b9dc249e-53ce-11e7-923a-95d7e896a384 1 
END RequestId: b9dc249e-53ce-11e7-923a-95d7e896a384 
REPORT RequestId: b9dc249e-53ce-11e7-923a-95d7e896a384 Duration: 2. 

任何幫助,非常感謝!

編輯:

萬一頂端回答不工作,這也適用:

var async = require('async'); 

exports.handler = (event, context, callback) => { 

async.waterfall([ 
     myFirstFunction, 
     mySecondFunction, 
     async.apply(myLastFunction, 'deen'), 
    ], function (err, result) { 
     callback(null,'done'); 
    }); 
}; 

function myFirstFunction(done) { 
     console.log('1'); 
     done(null, 'one', 'two'); 
    } 
    function mySecondFunction(arg1, arg2, done) { 
     // arg1 now equals 'one' and arg2 now equals 'two' 
     console.log('2'); 
     done(null, 'three'); 
    } 
    function myLastFunction(arg1, arg2, done) { 
     // arg1 is what you have passed in the apply function 
     // arg2 is from second function 
     console.log('3'); 
     done(null, 'finished the functions'); 
    } 

回答

1

你有一個回調傳遞給每個函數,告訴異步下一個功能應該運行。

這比使用承諾要複雜得多,但我們會一起去做。

async.waterfall([ 
    (next) => { 
    console.log(1); 
    next(2); 
    }, 
    (valueIs2, next) => { 
    console.log(valueIs2); 
    next(valueIs2 + 1, valueIs2 - 1); 
    }, 
    (valueIs3, valueIs1, next) => { 
    next(valueIs3 - valueIs1); 
    }, 
], (error, result) => 
    console.log(error ? `Error: ${error}` : `Result: ${result}`)); 
1

你錯過了瀑布任務的內部回調,它告訴程序去下一個任務。

所以,你只需要在代碼中添加一個回調,也將努力:

var async = require('async'); 

exports.handler = (event, context, callback) => { 

async.waterfall([ 
    function func1(done){ 
     console.log('1'); 
     done(); // now this will go to next task 
    }, 
    function func2(done){ 
     console.log('2'); 
     done(); // now this will go to next task 
    }, 
    function func3(done){ 
     console.log('3'); 
     done(null); // => err = null 
    }, 
], function (error, success) { 
    if (error) { console.log('Something is wrong!'); } 
    callback(null, 'success'); 
}); 
}; 

檢查上述文件:https://caolan.github.io/async/docs.html#waterfall

+0

你沒有錯,但這個傢伙上面首次在這裏與同樣的邏輯。 +1 – booky99