问题
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