Promise 的返回值 [英] return value from Promise

查看:121
本文介绍了Promise 的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑示例:

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

Console.log (returnValue ())

我该怎么做才能真正拥有someThing"或someError"?而不是一个未决的承诺?

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

请注意......当我在Meteor.methods"中编写这样的代码时,它的工作方式与我想要的完全一样,也就是说,它返回一个我返回给客户端的值,但在Meteor.methods"之外.方法"或在客户端(浏览器,使用或不使用任何框架)中,我拥有的是一个未决的承诺.

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.

推荐答案

传递给 .then() 的函数异步返回结果.已实现的 PromisePromise value 将可用作传递函数的参数.Console.log (returnValue ()),正如您所指出的,记录的是 Promise 本身,而不是 Promise value.将 .then() 链接到 returnValue() 调用.另外,Console.log(returnValue())应该是console.log().

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)
})

这篇关于Promise 的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆