2014-09-22 72 views
0

我有一個請求處理程序,做的東西像下面這樣的特定路線:的NodeJS請求處理程序不等待函數返回

function doThing(req, res) { 
    res.json({ "thing" : "thing", "otherThing": externalModule.someFunction("yay"); }); 
} 

好像結果是送「someFunction」通話結束前,所以「otherThing」JSON總是不存在。如何等待該函數在發送響應之前返回數據?

回答

1

使用回調。例如:

externalModule.someFunction = function(str, cb) { 
    // your logic here ... 

    // ... then execute the callback when you're finally done, 
    // with error argument first if applicable 
    cb(null, str + str); 
}; 

// ... 

function doThing(req, res, next) { 
    externalModule.someFunction("yay", function(err, result) { 
    if (err) return next(err); 
    res.json({ "thing" : "thing", "otherThing": result }); 
    }); 
}