簡體   English   中英

使用異步函數從Node.js模塊返回值

[英]Return value from Node.js module with asynchronous function

我為我的Node.js項目編寫了一個模塊,它處理一些數據並且應該返回結果,如下所示:

var result = require('analyze').analyzeIt(data);

問題是analyze.js依賴於異步函數。 基本上它看起來像這樣:

var analyzeIt = function(data) {
    someEvent.once('fired', function() {
        // lots of code ...
    });
    return result;
};
exports.analyzeIt = analyzeIt;

當然,這不起作用,因為返回時result仍然是空的。 但是我該怎么解決呢?

你可以用它在API中解決它的方式來解決它:使用回調,它可能是一個簡單的回調,一個事件回調或一個與某種類型的promise庫相關的回調。 前兩個更像Node,承諾的東西非常好吃。

這是簡單的回調方式:

var analyzeIt = function(data, callback) {
    someEvent.once('fired', function() {
        // lots of code ...

        // Done, send result (or of course send an error instead)
        callback(null, result); // By Node API convention (I believe),
                                // the first arg is an error if any,
                                // the second data if no error
    });
};
exports.analyzeIt = analyzeIt;

用法:

require('analyze').analyzeIt(data, function(err, result) {
    // ...use err and/or result here
});

但是正如Kirill指出的那樣 ,你可能想要analyzeIt返回一個EventEmitter ,然后發出一個data事件(或者你喜歡的任何事件),或者error時出錯:

var analyzeIt = function(data) {
    var emitter = new EventEmitter();

    // I assume something asynchronous happens here, so
    someEvent.once('fired', function() {
        // lots of code ...

        // Emit the data event (or error, of course)
        emitter.emit('data', result);
    });

    return emitter;
};

用法:

require('analyze').analyzeIt(data)
    .on('error', function(err) {
        // ...use err here...
    })
    .on('data', function(result) {
        // ...use result here...
    });

或者,再一次,某種承諾庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM