2016-10-29 23 views
0

NodeJSでコーディングを開始しましたが、1つの質問があります。私はこの場所にこだわっている。私はNodeJSが非同期であることを知っていますが、いつでも私は 'GET'を行う/空白の応答を得ます。NodeJSレスポンス非同期

/* GET home page. */ 
    router.get('/', function(req, res, next) { 
     var tenantID = 1; //Hardcoded TODO: Remove this value later 
     var dwelltest = dwellTimeBucketModel.fetchFromDB(tenantID); 
      //I have a model in which I do all the DB calls (Cleaner to seperate?) 
     res.json({dwell: dwelltest}); //Send response back 
    } 

私はこれを行うたびに、私の応答は空白に送られます。 (これは非同期動作によるものだとわかっています)。私はそれを働かせる方法がわからないのですか?

私はこれやってみました:

var dwellResult = new Promise(function(resolve, reject){ 
    dwellTimeBucketModel.fetchFromDB(tenantID); 
}); 

dwellResult.then(function (result) { 
    console.log(result); 
    res.json({dwell: result}) 
}).catch(function (error) { 
    console.error(error); 
}) 

をしかし、応答が送信されることはありません。私は何が間違っているのか分かりません。

私は適切な練習をしていますか?あなたは約束の構文を見ている場合(または標準?)

おかげ

答えて

3

ここでは、ここで

var p = new Promise(function(resolve, reject) {  
    // Do an async task async task and then... 

    if(/* good condition */) { 
     resolve('Success!'); 
    } 
    else { 
     reject('Failure!'); 
    } 
}); 

p.then(function(response) { 
    /* do something with the result */ 
}).catch(function() { 
    /* error :(*/ 
}) 

が2以上詳述されているIS-約束

var dwellResult = new Promise(function(resolve, reject){ 
    resolve(dwellTimeBucketModel.fetchFromDB(tenantID)); 
}); 
関連する問題