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));
};
嗯,我看,我不得不承認,我忘了這一點,但現在當我想它,因爲我使用的藍鳥,而不是原生的承諾,在藍鳥的承諾的背景下會不會這樣? 我必須嘗試一下:-) – AuHau
不,箭頭功能是一種語言功能。使用哪種承諾實現無關緊要。 – Bergi
我明白了!我只是測試它,它的工作!謝謝! :-) – AuHau