简体   繁体   中英

Using promises in sync code

I would like to know if is it wrong use promises in sync code.

I have a entry point file and inside i have a gigant code like:

Promise.resolve(MAP)
  .then((MAP) => {

    return taskOne();
  })
  .then((MAP) => {

    return taskTwo();
  })
  .then((MAP) => {

    return taskThree();
  });

And so on, until taskTen.

Inside each task, i have sync code, and in the final, i'm just returning the new value of MAP, like:

function taskOne(MAP) {
  // DO SOMETHING

  return MAP;
}

I feel nice doing that, but i don't know.. Maybe i'm doing it wrong.

Thanks.

First off, asynchronous code is pretty much always more complicated than synchronous code so I've never seen a reason when I wanted to take something that is always synchronous and make it asynchronous. And using promises with .then() forces your synchronous code to now become asynchronous.

Second off, your scheme whether written using promises or not is full of repeated code. I'd suggest you DRY it up rather than just copy the same sequence over and over. And while you're DRYing it up, you will probably find there's no longer a reason to use promises as you can solve your problem more succinctly in a synchronous fashion.

If all your functions take the same argument and you just want to pass along the return result of one to the next, then I'd suggest you just put the functions in an array and iterate through the array and .reduce() is a built-in design pattern for passing a result along from one to the next:

var fns = [taskOne, taskTwo, taskThree, taskFour, taskFive, taskSix, taskSeven, taskEight, taskNine, taskTen];

var final = fns.reduce(function(m, fn) {
    return fn(m);
}, MAP);

FYI, this pattern can be slightly modified to work if your functions are actually async and return promises, but I wouldn't suggest you switch to that until your functions actually are async:

var fns = [taskOne, taskTwo, taskThree, taskFour, taskFive, taskSix, taskSeven, taskEight, taskNine, taskTen];

fns.reduce(function(p, fn) {
    return p.then(fn);
}, Promise.resolve(MAP)).then(function(final) {
    // all done here
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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