gpt4 book ai didi

javascript - 将值从 'this' 传递到 Promise 的 'then' 函数的正确方法

转载 作者:行者123 更新时间:2023-11-28 18:56:33 27 4
gpt4 key购买 nike

我试图了解如何在 JS 中正确使用 Promise,但我偶然发现了以下问题。

如何正确/有效/以最佳方式将值传递给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));
};

最佳答案

鉴于您已经在使用箭头函数,因此绝对不需要此封闭的 calendar 变量 - 箭头函数确实会按词法解析其 this 值。

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

关于javascript - 将值从 'this' 传递到 Promise 的 'then' 函数的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33528155/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com