2016-11-19 46 views
-2

我花了這麼多時間試圖找到這裏這個問題的答案,並拿出什麼利用數據。希望有人能開導我..的Javascript:從一個異步回調函數(MongoClient)

我有一個代碼,它正在對數據庫進行異步調用,並在回調函數中返回數據(在我的例子中,我使用的是MongoClient,它返回一個Promise)。不過,我不知道如何使用所產生的數據實際設置功能級別的變量 - 每當我試圖這樣做所產生的價值,我登錄是未定義或掛起的承諾目標。

有很多關於這個問題的帖子,但我不能找到工作,當我嘗試應用它們的任何方法。任何和所有的幫助感激地收到!

function lookupOneDbEntry(key, value) { 

    var responseData = "initial data" 

    // search for the entry in the database 
    db.collection("my_collection").findOne({key: value}, function(err, result) { 
     if (err) { 
     //if database throws an error 
     responseData = "db error"; 
     } 
     else { 
     // if the entry is found, return the data 
     responseData = result; 
     } 
    }); 

    return responseData; 

    } 

編輯:我知道其他職位上這個(像這樣的here和,而詳盡的文件是在一定程度上是有用的,我,M在現實生活中實現,如實際使用此信息有問題上面的一個。因此,我的問題在這裏。

+1

可能重複[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an -asynchronous-call) – Andreas

+0

你連接的這個問題確實有你需要的所有信息。克林先生的回答有很多解釋和針對不同情況的各種解決方案。 – Pointy

+0

你能告訴你如何使用Promise嗎? – Victory

回答

0

異步調用發生,你是在調用堆棧之外。你無法將其返回到當前堆棧。

所以我們使用的承諾掛鉤到結果我們的電話。

function lookupOneDbEntry(key, value) { 
    return new Promise(function (resolve, reject) { 
    // search for the entry in the database 
    db.collection("my_collection").findOne({key: value}, function(err, result) { 
     if (err) { 
     //if database throws an error 
     reject(err); 
     } 
     else { 
     // if the entry is found, return the data 
     resolve(result); 
     } 
    }); 
    }); 
} 

lockupOneDbEntry('myKey', 'myValue').then(function (result) { 
    console.log('result', result); 
}, function (err) { 
    console.log("error!", err); 
}); 
+0

欣賞努力,但這並不適合我。謝謝你把我拉到雖然解決許的想法,我好不容易纔湊齊基於這種想法的解決方案:) – user2521119

+0

沒問題。如果它有幫助,你應該upvote,如果你找到解決方案解釋它,你可以在這裏回答你自己的問題,它的鼓勵。 – Victory

0

很長一段時間的實驗,我終於成功地做到這一點後 - 我並不需要在最後任何花哨的回調或額外承諾,我只是刪除的數據庫請求可選的回調,而是處理返回的承諾分別。

function lookupOneDbEntry(key, value) { 

    var responseData = "initial data"; 

    var solution = db.collection("accounting_module").findOne({key: value}); 

    solution.then(function (result) { 
     // validation of result here 
     responseData = result; 
    }); 

    return responseData; 
}