gpt4 book ai didi

javascript - Bluebird 无极绑定(bind)链

转载 作者:搜寻专家 更新时间:2023-10-31 22:49:31 26 4
gpt4 key购买 nike

我将 Bluebird 用于 promises 并尝试允许链式调用,但是使用 .bind() 似乎不起作用。我得到:

TypeError: sample.testFirst(...).testSecond is not a function

第一个方法被正确调用并启动了 promise 链,但我根本无法使实例绑定(bind)工作。

这是我的测试代码:

var Promise = require('bluebird');

SampleObject = function()
{
this._ready = this.ready();
};

SampleObject.prototype.ready = function()
{
return new Promise(function(resolve)
{
resolve();
}).bind(this);
}

SampleObject.prototype.testFirst = function()
{
return this._ready.then(function()
{
console.log('test_first');
});
}

SampleObject.prototype.testSecond = function()
{
return this._ready.then(function()
{
console.log('test_second');
});
}

var sample = new SampleObject();
sample.testFirst().testSecond().then(function()
{
console.log('done');
});

我正在通过以下方式使用最新的 Bluebird :

npm install --save bluebird

我是不是处理错了?我将不胜感激任何帮助。谢谢。

最佳答案

它抛出该错误是因为 testFirst 上没有方法 testSecond ,如果您想在两个 Promises 都解决后做某事,请按以下方式进行:

var sample = new SampleObject();

Promise.join(sample.testFirst(), sample.testSecond()).spread(function (testFirst, testSecond){
// Here testFirst is returned by resolving the promise created by `sample.testFirst` and
// testSecond is returned by resolving the promise created by `sample.testSecond`
});

如果你想检查两者是否都正确解析,而不是执行 console.log ,返回 testFirsttestSecond 函数中的字符串并将它们记录在 spread 回调如下所示:

SampleObject.prototype.testFirst = function()
{
return this._ready.then(function()
{
return 'test_first';
});
}

SampleObject.prototype.testSecond = function()
{
return this._ready.then(function()
{
return 'test_second';
});
}

现在,如下所示在 spread 回调中执行 console.log,将记录上述 promise 返回的字符串:

Promise.join(sample.testFirst(), sample.testSecond()).spread(function(first, second){
console.log(first); // test_first
console.log(second); // test_second
});

关于javascript - Bluebird 无极绑定(bind)链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41561842/

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