解析.然后方法和链接|语法让我迷惑



亲爱的stackoverflow社区,

我正在使用应用程序工艺作为JS云IDE,并集成Parse的云数据库进行存储。

我正在编写一个订阅服务,想要检查用户是否已经订阅,然后验证他们的使用或提示他们注册。作为一个异步调用,我试图利用Parse的/Promise的。then方法在继续之前等待服务器的响应。

我已经阅读了Parse网站上的示例和样本(之前的链接),但仍然无法理解它。

此代码起作用,如果找到匹配,则返回电子邮件地址:

      ... *Parse declaration etc*  
query.find({
            success: function(results){
                if(results.length>0){
                    app.setValue("lblOutput", results[0].attributes.email);
                }
                else{
                    app.setValue("lblOutput", "No match.");
                }
            },
            error: function(object, error){
                console.log(error.message);
                console.log(object);
            }
        });  

我的链接尝试,最近的一次:

    query.find().then(function(results) {
        if(results){
            console.log("Within the Then!");
            console.log(results);
        }
        else{
            console.log("Could be an error");
        }
    });

声明方法或属性'success'对undefined无效。我试图结合第一个函数的语法(成功:…)//错误:…)链接失败

有什么建议吗

  1. 检查是否有邮件存在于Parse DB中,然后
  2. 等待结果返回,以便使用另一个函数进行进一步操作

非常感谢。

一旦我有了。then(),就会有更多的异步等待层。

欢呼,詹姆斯

你的语法是不正确的,它应该是:

query.find().then(
    function(results) {    
        console.log("Within the Then!");
        console.log(results);    
    },
    function(error){
        console.log("Could be an error"+error);
    }
);

then()函数接受一个或两个函数。

第一个是成功处理器,第二个是错误处理器。

query.find()(成功,错误)

这个片段没有经过测试,但是应该非常接近。

var query = new Parse.Query(Parse.User);
query.equalTo(email, "me@me.com");  
query.count().then(
    function(resultsCount) {    
        //success handler
        if(resultsCount > 0){
            doSomeOtherFunction();
        }
    },
    function(error){
        //error handler
        console.log("Error:"+error);
    }
);

如果你有更多的异步工作要做,你的方法应该看起来像这样,记住,当链接承诺最后then()应该包含你的错误处理。

query.find().then(function(result){
  doSomethingAsync(); //must return a promise for chaining to work!
}).then(function(result1){
  doSomethingAsync2(); //must return a promise for chaining to work!
}).then(function(result2){
  doSomethingAsync3(); //must return a promise for chaining to work!
}).then(null,function(error){
  // an alternative way to handle errors
  //handles errors for all chained promises.
})

最新更新