取消延迟的Bluebird承诺

时间:2015-09-30 17:24:05

标签: javascript promise bluebird

如何拒绝延迟的承诺:

vector<vector<iterc>> res;
res.resize(altoPantalla);

for (int i = 0; i < altoPantalla; i++){
   res[i].resize(anchoPantalla);
}

int numThreads = 10;
vector<thread> workers(numThreads);

for (int i = 0; i < numThreads; i++){ //here diferent try
   thread workers[i] (calcIterThread, ref(res), inicio, fin, i)); // error: expresion must have a constant value
   workers[i] = thread(calcIterThread, ref(res), inicio, fin, i)); // error: no instance of constructor "std::thread::thread" matches the argument list
}

...rest of code... 

1 个答案:

答案 0 :(得分:8)

Bluebird v3

我们不再需要将Promise声明为'可取消'(documentation):

  

取消工作无需设置代码

只需在承诺上致电cancel

const promise = new Promise(function (_, _, onCancel) {
    onCancel(function () {
        console.log("Promise cancelled");
    });
});

promise.cancel(); //=> "Promise cancelled"

您可能已经注意到,cancel方法不再接受取消原因作为参数。取消所需的逻辑可以在赋予onCancel的函数内声明,finally是赋予Promise构造函数执行器的第三个参数。或者在const removeDelay = Promise .delay(5000) .then(() => removeSomething()); removeDelay.cancel(); 回调中,因为当Promise被取消时也不会被视为错误。

修订示例:

.cancellable()

______

Pre Bluebird v3

查看Promise#cancellable的文档:

  

默认情况下,承诺不可取消。可以使用const removeDelay = Promise .delay(5000) .cancellable() // Declare this Promise as 'cancellable' .then(() => removeSomething()); .catch(err => console.log(err)); // => 'Reason for cancel' removeDelay.cancel('Reason for cancel'); 将承诺标记为可取消。如果未解决,可以取消可取消的承诺。取消承诺会传播到仍然未决的目标承诺的最远可取消祖先,并在给定原因下拒绝该承诺,或默认情况下CancellationError

我们可以像这样使用它:

[^whatever]