如何从解析查询返回对象

How to return an object from a Parse query?

本文关键字:查询 返回 对象      更新时间:2023-09-26
这是我

的做法:

  const Document = Parse.Object.extend('Document')
  const query = new Parse.Query(Document)
  let result = {}
  query.get(id, {
    success: function (object) {
      result = object.toJSON()
      console.log(result)
    },
    error: function (object, error) {
      alert(`Error: ${error.code} ${error.message}`)
    }
  })
  console.log(result)
  return result

第一个console.log(result)输出对象:

对象 {内容: "trstrtrts", 创建于: "2016-01-17T11:20:30.694Z", 标题:"文档 2",更新于:"2016-01-17T11:20:30.694Z",字数: "3000"...}

但是第二个什么也没返回。从 Parse 查询返回对象的正确方法是什么?

编辑:

根据匿名者的回答,我尝试了这个:

店铺.js:

store.first = (id) => {
  var query = new Parse.Query(Document)
  return query.get(id)
}
export default store

主.js:

store.first(to.params.id).then((document) => {
   console.log(document.toJSON())
   return document.toJSON()
 })

但是我收到以下错误:

未捕获的类型错误:对象函数 ParsePromise() { _classCallCheck(这个,ParsePromise);this._resolved = 假;this._rejected = 假;this._resolvedCallbacks = []; this._rejectedCallbacks = [];} 没有方法 'all'

第二个

 console.log(result) 

在第一个之前发生。查询是一种异步操作。正确的方法是使用承诺。例如,你可以做

function foo(id){
     var Document = Parse.Object.extend('Document');
     var query = new Parse.Query(Document);
      return query.get(id);
}

然后像这样使用函数 foo:

foo(objectID).then(function(object){
  //do something with the object.
})

下面是一个在 js 中显示异步的示例。

     console.log('a');
     setTimeOut(function(){console.log('b')},0);
     console.log('c');

打印顺序为 一个 c 乙

(我们有超时 0,但超时函数进入事件循环并在函数完成后发生)

有关更多信息,您可以阅读 https://developer.mozilla.org/he/docs/Web/JavaScript/EventLoop关于事件循环