Convert promise to synchronous function

三世轮回 提交于 2020-01-24 20:52:26

问题


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.



来源:https://stackoverflow.com/questions/31620949/convert-promise-to-synchronous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!