像Q一样定义空蓝鸟的承诺

Fez*_*sta 36 javascript promise q bluebird

有了QI可以定义一个新的承诺:

var queue = q();
Run Code Online (Sandbox Code Playgroud)

但是如果我这样做,那就是Bluebird:

var queue = new Promise();
Run Code Online (Sandbox Code Playgroud)

我明白了:

TypeError: the promise constructor requires a resolver function
Run Code Online (Sandbox Code Playgroud)

如何获得与Q相同的结果?

这是我的代码片段:

var queue    = q()
    promises = [];
queue = queue.then(function () {
    return Main.gitControl.gitAdd(fileObj.filename, updateIndex);
});
// Here more promises are added to queue in the same way used above...
promises.push(queue);
return Promise.all(promises).then(function () {
   // ...
});
Run Code Online (Sandbox Code Playgroud)

Ben*_*aum 37

弗洛里安提供了很好的回答你原来的问题的原因,有几种方法来启动与蓝鸟链.

其中一个最简单的就是Promise.resolve()什么都不要求:

var queue = Promise.resolve(); //resolve a promise with nothing or cast a value
Run Code Online (Sandbox Code Playgroud)

要么

Promise.try(function(...){
    return ...//chain here
});
Run Code Online (Sandbox Code Playgroud)

所以你可以这样做:

var queue    = Promise.resolve()
    promises = [];
queue = queue.then(function () {
    return Main.gitControl.gitAdd(fileObj.filename, updateIndex);
});

// Here more promises are added to queue in the same way used above...
promises.push(queue);
return Promise.all(promises).then(function () {
   // ...
});
Run Code Online (Sandbox Code Playgroud)

虽然,我个人会这样做:

//arr is your array of fileObj and updateIndex

Promise.map(arr,function(f){ return Main.gitControl.gitAdd(f.filename,f.updateIndex).
    then (function(result){
        //results here
    });
Run Code Online (Sandbox Code Playgroud)

  • 为什么`Promise.resolve()`比'Promise.cast()`更好? (3认同)
  • @FlorianMargaine好问题,Promsie.resolve在ES6规范中,当API创建时,Promise.cast和Promise.resolve都在ES6规范和Bluebird中,我认为`.cast`将在Bluebird 2.0中被删除. (3认同)
  • `Bluebird.defer()`和`Bluebird.cast()`在2.x版本中都被弃用了,要创建一个"干净"的promise链,最好使用`Bluebird.resolve()` (3认同)

Flo*_*ine 23

var resolver = Promise.defer();
setTimeout(function() {
    resolver.resolve(something); // Resolve the value
}, 5000);
return resolver.promise;
Run Code Online (Sandbox Code Playgroud)

这一行经常在文档中使用.

请注意,这通常是使用它的反模式.但如果你知道自己在做什么,那么就Promise.defer()可以通过类似Q的方式获得旋转变压器.

但是,不鼓励使用这种方法.蓝鸟甚至已弃用它.

相反,你应该使用这种方式:

return new Promise(function(resolve, reject) {
    // Your code
});
Run Code Online (Sandbox Code Playgroud)

请参阅相关文档位:Promise.defer()新的Promise().


在您的问题更新后,这是您的问题:您正在重复使用相同的承诺来解决多个值.承诺只能解决一次.这意味着你必须使用Promise.defer()你承诺的次数.

也就是说,在看到更多代码之后,似乎你真的在使用反模式.使用promises的一个优点是错误处理.对于您的情况,您只需要以下代码:

var gitControl = Promise.promisifyAll(Main.gitControl);
var promises = [];
promises.push(gitControl.gitAddAsync(fileObj.filename, updateIndex));
return promises;
Run Code Online (Sandbox Code Playgroud)

这应该足以处理您的用例.它更清晰,它还具有真正正确处理错误的优势.

  • @FlorianMargaine +1你能解释一下为什么`新的Promise(函数(...`比使用`Promise.defer()更受欢迎?)只是因为它"笨拙"而且"容易出错"? (4认同)