return value from Promise

戏子无情 提交于 2019-12-13 06:47:19

问题


Considering the example:

function returnValue () {
   return somePromise.then (
     function (someThing) {
       return {
         sucess: true,
         data: someThing
       }
     },
     function (someError) {
       return {
         sucess: false,
         data: someError
       }
     }
   )
}

Console.log (returnValue ())

What should I do so that I actually have "someThing" or "someError"? And not a Promise pending?

Just to note ... when I write a code like this within "Meteor.methods" it works exactly as I would like, that is, it returns a value that I return to the client, but outside of "Meteor.methods" or in the client (browser, using or not any framework) the one I have is a Promise pending.


回答1:


The function passed to .then() returns results asynchronously. The Promise value of the fulfilled Promise will be available as the argument of the passed function. Console.log (returnValue ()), as you noted, logs the Promise itself, not the Promise value. Chain .then() to returnValue() call. Also, Console.log (returnValue ()) should be console.log().

let somePromise = Promise.resolve("abc");

function returnValue () {
   return somePromise.then (
     function (someThing) {
       return {
         sucess: true,
         data: someThing
       }
     },
     function (someError) {
       return {
         sucess: false,
         data: someError
       }
     }
   )
}

returnValue().then(function(result) {
  console.log(result)
})


来源:https://stackoverflow.com/questions/41190820/return-value-from-promise

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