【问题标题】:How to return an object from a Parse query?如何从 Parse 查询中返回对象?
【发布时间】:2016-01-17 21:06:53
【问题描述】:

这就是我的做法:

  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”,createdAt:“2016-01-17T11:20:30.694Z”, 标题:“文档 2”,更新时间:“2016-01-17T11:20:30.694Z”,字数: “3000”…}

但是第二个没有返回任何内容。从 Parse 查询返回对象的正确方法是什么?

编辑:

根据 Anon 的回答,我尝试了这个:

store.js:

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

export default store

ma​​in.js:

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

但我收到以下错误:

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

【问题讨论】:

    标签: javascript parse-platform


    【解决方案1】:

    第二个

     console.log(result) 
    

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

    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 b

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

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

    【讨论】:

    • 感谢您的回答。但我得到一个类型错误:Uncaught TypeError: Object function ParsePromise() { _classCallCheck(this, ParsePromise); this._resolved = false; this._rejected = false; this._resolvedCallbacks = []; this._rejectedCallbacks = []; } has no method 'all'
    • 它应该可以工作,也许是 const 的问题 .. 尝试使用 var 来检查
    • 同样的问题。也许是因为我必须设置 resolvereject 回调?
    • 没有。这不是决定/拒绝。我去看看
    • 哦,我忘了 foo()。然后我写的是 foo.then。你必须写 foo().then()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多