【发布时间】:2016-07-24 11:40:03
【问题描述】:
我的问题涉及承诺和提供链承诺的先前值。问题是,项目是否从第一个返回承诺传递到第二个承诺“runItem --> testItem”?
或者我们是否必须通过所有承诺传递项目?
例子:
db.items.find({_id: id}).then(function (res) {
runItem(item);
})
function runItem(item) {
removeFromQueue(item.id).then(function () {
testItem(item);
});
}
function testItem(item) {
...
}
function removeFromQueue(item) {
return db.queue.remove({_id: item._id});
}
编辑: 也许这是一个更好的例子:
我们可以访问原始属性项,还是在下次调用函数时会被覆盖?
function start(id)
db.find({_id: id}).then(function (item) {
test(item).then(function (res) {
// can we access original attribute item, or is it going to be overwritten when the next time function is called
resolve({ res: res, item: item });
});
});
}
function test(item) {
return $test(item).then(function () {
resolve('success');
});
}
【问题讨论】:
-
你应该返回承诺对象。
-
我不明白你想用你的代码做什么,但是不,以前的值没有被存储,如果你需要它们,你必须保存它们(在某些情况下它很方便使用 bluebird promise 绑定到对象的能力。
-
我想将“item”传递给testItem函数,但“item”是runItem函数中的一个属性。代码是通用的,主要是我只想知道,如果有可能,如果没有,将变量从一个承诺传递到另一个承诺的最佳方式是什么。
-
也许可以,但我更喜欢我的示例的解决方案,因为我项目中的大部分代码都是这样组织的。
标签: javascript promise bluebird