简体   繁体   English

在节点 js 中调用方法时,返回的值是 [object Promise],因为控制台输出正在打印值

[英]when calling a method in node js the value returned is [object Promise] were as the console output is printing the value

I am a newbie to nodejs and promises, i am trying to fetch some data from json and pass them to other function for further processing, here is my code.我是 nodejs 和 promises 的新手,我试图从 json 中获取一些数据并将它们传递给其他函数进行进一步处理,这是我的代码。

const test = tests.fetchAll().then(test1 => {
    const testsDataArray = JSON.parse(JSON.stringify(test1))
    const testsData = testsDataArray.data
    const testsId = testsData.find(iid => iid.ips === '1.2.3.4')
    // console.log(testsId.id)
    console.log(testsId)
    return testsId.id.toString()
  })

this has a json which is used in the above code这有一个 json 用于上面的代码

{
  id: 36,
  name: 'p ',
  seats: 10,
  description: 'Test description',
  contact: 'p@xyz.com',
  created_at: '2019-12-31T11:18:19.000Z',
  updated_at: null,
  ips: '1.2.3.4',
  domains: 'xyz.com',
  termination_date: null,
  seats_used: null
}

when I run the following code :当我运行以下代码时:

test.then(result => {
    console.log(result)
  })

the output printed on console is '36', where as when i return the same, it returns [object Promise]控制台上打印的输出是“36”,当我返回相同的输出时,它返回 [object Promise]

test.then(result => {
        console.log(result)
      })

In your code, test is a promise.在您的代码中, test是一个承诺。 The ONLY way to get the value from it is is inside a .then() handler or by using await on the promise.从中获取值的唯一方法是在.then()处理程序中或通过在 promise 上使用await

If you add return result to your .then() handler, that just keeps result as the resolved value of the next promise.如果您将return result添加到您的.then()处理程序,那么result只会作为下一个承诺的解析值。 It doesn't magically make result a regular, non-asynchronous return value.它不会神奇地使result成为常规的、非异步的返回值。

Please remember that promise.then() returns ANOTHER promise.请记住promise.then()返回另一个承诺。 So, returning a value from a .then() handler just makes it the resolved value of this additional promise that is returned.因此,从.then()处理程序返回一个值只会使它成为返回的这个附加承诺的解析值。

So, if you did this:所以,如果你这样做:

const p = test.then(result => {
    return result;
});
console.log(p);          // this is still just a promise

All, you've done is made a new promise with test.then() and made result the value of that new promise.你所做的就是用test.then()做出一个新的承诺,并让result成为那个新承诺的价值。 You STILL have to use .then() or await on p to get the value from it.您仍然必须使用.then()await on p才能从中获取值。 You always have to get a value out of a promise with .then() or await no matter how many times you return it from a .then() handler or from an async function.无论您从.then()处理程序或async函数返回多少次.then()您始终必须从.then()await的承诺中获取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM