Promise循环(bluebird) - 在异步中包装对象

时间:2015-02-17 21:34:43

标签: javascript promise bluebird

我对承诺有疑问。

我正在使用Bluebird Promise库并使用它构建一个小的异步

我正在尝试使用函数来实现瀑布承诺。

说我像这样使用承诺:

Promise.resolve()
.then(function () {
  console.log("called 1")
  return 1;
}).then(function () {
  return new Promise (function (res, rej) {
    setTimeout(function () {
      console.log("called 2")
      res(2);  
    }, 1500);
  });
}).then(function () {
  console.log("called 3")
  return 3;
});

实际上这确实在循环中等待并按顺序返回1,2,3。

如何将其包装到函数中,以便我可以执行以下操作:

a();b();c();,或a().b().c();其中a()将某些东西放到链上,b()将某些东西放到链上,然后c()将某些东西按顺序放到链上。

从那以后()返回一个新的promise,它可以全部乱序,所以像 不起作用:

var promise = Promise.resolve();
function a () {
  promise.then(function () { 
    // do sync/async 
  });
}
function b () {
  promise.then(function () {
    //do sync/async
  });
}
function c ...

感谢您的时间:]

  

我不确定这里的目标是什么。您是否希望在预先知道序列的情况下按顺序运行任意数量的事物?或者这是一个在你去的时候发现序列的情况? NodeJS流接口可以顺序处理未知数量的事物(@tadman)

序列是可发现的,目标是能够调用a().b().c()b().a().d()。客户端的异步库。

更新如果我这样做,@ serkms说它无法按预期工作。我的坏,应该工作正常,但缺乏上下文/代码没有给我足够的信息来扩展。仍然感谢你的回答,因为它给了我更多的思考。

更新:查看我的回答

2 个答案:

答案 0 :(得分:1)

你可以使用scoped prototype并在那里添加那些方法

Promise.prototype.a = function() {
  return this.then(function() {
    console.log("called 1")
    return 1;
  });
};

Promise.prototype.b = function() {
  return this.delay(1500).then(function() {
    console.log("called 2")
    return 1;
  });
};

Promise.prototype.c = function() {
  return this.then(function() {
    console.log("called 3")
    return 3;
  });
};

我用它来创建整洁的DSL,例如用git:

https://gist.github.com/petkaantonov/6a73bd1a35d471ddc586

答案 1 :(得分:0)

感谢@tadman我到目前为止想出了这个,似乎按照我的预期工作。 问题是我在调用它之前没有更新promise,它是分支而不是按顺序调用它。 这就是我想要的 - 将同步/异步的对象转换为异步以允许链接。 Petka(@Esailija)也展示了通过扩展bluebird库来构建上面的DSL(semvar版本碰撞和git推送)的很好的例子,但就我的目的而言,这已经足够了。

var Sample = function () {
  this.promise = Promise.resolve();
};

Sample.prototype.a = function () {
  this.then(function () {
    console.log("1");
  });
  return this;
};

Sample.prototype.b = function () {
  this.then(function () {
    return new Promise(function (res, rej) {
      setTimeout(function() {
        console.log("2");
        res();
      }, 500);
    });
  });
  return this;
};

Sample.prototype.c = function () {
  this.then(function () {
    console.log("3");
  })
  return this;
};

Sample.prototype.chainPromise = function (func) {
  this.promise = this.promise.then(func);
};

var s = new Sample();
s.a().b().c();

甚至是代替chainPromise?

Sample.prototype.then = function (func) {
  this.promise = this.promise.then(func);
  return this.promise;
};