Convert promise to synchronous function

2019-08-08 08:53发布

问题:

If I have a simple function like this one below addTwo I can use bluebird's Promise.method(addTwo) to make it a promise, even though it doesn't perform any async operations. Is there any way to do the opposite of this?

function addTwo(num){
  return num + 2
}

var newValue = addTwo(2) // => 4

addTwoPromise = Promise.method(addTwo)

addTwoPromise(2).then(function(newValue){
  console.log(newValue) // == 4
})

Is there any way to convert addTwoPromise from a promise to a synchronous function again? I know all about async / await and I'm not looking for that as the answer.

回答1:

Yes, you can use Promise.setScheduler to explicitly violate the Promises/a+ specification and force bluebird to run then callbacks synchronously.

Please don't, as it will only work for functions that are synchronous anyway (which shouldn't return promises to begin with) and it will create one hell of a race condition.