在JavaScript中实现异步Promises的工具:q

jopen 9年前

一个工具用于在JavaScript中制作和编写异步Promises。Promises是一种令代码异步行为更加优雅的抽象,它很有可能是JavaScript的下一个编程范式,一个Promise即表示任务结果,无论该任务是否完成。 每个Promise都拥有一个叫做then的唯一接口,当Promise失败或成功时,它就会进行回调。它代表了一种可能会长时间运行而且不一定必须完成的操作结果。这种模式不会阻塞和等待长时间的操作完成,而是返回一个代表了承诺的(promised)结果的对象。
q.png

On the first pass, promises can mitigate the “Pyramid of Doom”: the situation where code marches to the right faster than it marches forward.

step1(function (value1) {      step2(value1, function(value2) {          step3(value2, function(value3) {              step4(value3, function(value4) {                  // Do something with value4              });          });      });  });

With a promise library, you can flatten the pyramid.

Q.fcall(promisedStep1)  .then(promisedStep2)  .then(promisedStep3)  .then(promisedStep4)  .then(function (value4) {      // Do something with value4  })  .catch(function (error) {      // Handle any error from all above steps  })  .done();

项目主页:http://www.open-open.com/lib/view/home/1414637600090