2015-11-04 29 views
0

我想了解如何在JS中正確使用Promise,並且偶然發現了以下問題。正確的方式將'this'中的值傳遞給'promise'中的'then'函數

如何正確/有效/以最佳方式將值then Promise從this變量?

我正在開發使用Node.js,MongoDB和Mongoose的後端,並具有日曆模型,我正在使用方法getFilteredIcal進行擴展。現在我將this存儲到臨時變量calendar中,因此可以通過從then函數關閉來訪問,但我不喜歡這種方法,也認爲它是錯誤的。 看到我的代碼附加問題。

var Calendar = new mongoose.Schema({ 
    url: String, 
    userId: mongoose.Schema.Types.ObjectId 
}); 

Calendar.method.getFilteredIcal = function (respond) { 
    var fetch = require('node-fetch'); 
    var icalCore = require('../tools/icalCore'); 
    var calendar = this; // <-- I don't like this 
    fetch.Promise = require('bluebird'); 

    fetch(calendar.url) 
    .then(icalCore.parseIcal) 
    .then(parsedIcal => { return icalCore.filterIcal(parsedIcal, calendar._id) }) // <-- I need Calendar ID here 
    .then(icalCore.icalToString) 
    .done(icalString => respond.text(icalString)); 
}; 

回答

3

既然你已經使用箭頭功能,也絕對沒有必要爲此calendar變量被關閉了 - 箭頭功能做詞法解決他們this值。

fetch(calendar.url) 
.then(icalCore.parseIcal) 
.then(parsedIcal => icalCore.filterIcal(parsedIcal, this._id)) 
//             ^^^^ 
.then(icalCore.icalToString) 
.done(icalString => respond.text(icalString)); 
+0

嗯,我看,我不得不承認,我忘了這一點,但現在當我想它,因爲我使用的藍鳥,而不是原生的承諾,在藍鳥的承諾的背景下會不會這樣? 我必須嘗試一下:-) – AuHau

+0

不,箭頭功能是一種語言功能。使用哪種承諾實現無關緊要。 – Bergi

+0

我明白了!我只是測試它,它的工作!謝謝! :-) – AuHau

相關問題