简体   繁体   English

由于链而在同步操作中使用Promise

[英]Using promises in sync operation because of chain

i have this chain: 我有这个链条:

phase_one(files).then(phase_two).then(phase_three).then(phase_four);

Each phase will receive this array with object files inside. 每个阶段都将接收此数组,其中包含目标文件。 And inside each phases, i have this default piece of code: 在每个阶段中,我都有以下默认代码:

  return Promise.map(files, function(file) {
    // some code here
  }, {
    concurrency: 3000
  });

The problem is.. phase_two is synchronous... but i want still use the chain i shouldn't use the Promise.map. 问题是.. phase_two是同步的...但是我仍要使用链,我不应该使用Promise.map。

I would like to know if there is anything to help me with this in bluebird. 我想知道在bluebird中是否有什么可以帮助我的。 I search in the docs and i didn't find. 我在文档中搜索,但没有找到。

Thanks. 谢谢。

phase_two can just be a function that returns a value. phase_two可以只是一个返回值的函数。 The chain will continue just fine. 连锁店将继续很好。

phase_one(files).then(phase_two).then(phase_three).then(phase_four);

function phase_two(input) {
    // do something
    return result;
}

A .then() handler can be either synchronous or asynchronous. .then()处理函数可以是同步的也可以是异步的。 If it's asynchronous, then it must return a promise. 如果它是异步的,那么它必须返回一个Promise。 If it's synchronous, it can just return a value which become the value passed to the next part of the chain. 如果它是同步的,则可以只返回一个值,该值成为传递到链的下一部分的值。


The very first link in the chain must return a promise (to start the chain). 链中的第一个链接必须返回一个Promise(以启动链)。 If phase_one() is synchronous and you want to keep with the structure you had before, then you can just return Promise.resolve(data); 如果phase_one()是同步的,并且您希望保持以前的结构,则只需return Promise.resolve(data); from within phase_one() . phase_one() This will make the return value a promise which will have a .then() handler. 这将使返回值成为一个具有.then()处理函数的promise。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM