在返回函数变量之前,如何等待承诺完成? [英] How do I wait for a promise to finish before returning the variable of a function?

查看:188
本文介绍了在返回函数变量之前,如何等待承诺完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在努力应对承诺,但是由于社区在这里取得了一些进展。

I'm still struggling with promises, but making some progress thanks to the community here.

我有一个简单的JS函数来查询Parse数据库。它应该返回结果数组,但显然由于查询的异步性质(因此是promises),函数在结果之前返回,留下一个未定义的数组。

I have a simple JS function which queries a Parse database. It's supposed to return the array of results, but obviously due to the asynchronous nature of the query (hence the promises), the function returns before the results, leaving me with an undefined array.

我需要做些什么来使这个函数等待承诺的结果?

What do I need to do to make this function wait for the result of the promise?

这是我的代码:

function resultsByName(name)
{   
    var Card = Parse.Object.extend("Card");
    var query = new Parse.Query(Card);
    query.equalTo("name", name.toString());

    var resultsArray = [];

    var promise = query.find({
               success: function(results) {
               // results is an array of Parse.Object.
                             console.log(results);
                             //resultsArray = results;
                             return results;
               },

               error: function(error) {
               // error is an instance of Parse.Error.
                             console.log("Error");
               }
    });                           

}


推荐答案

而不是返回一个 resultsArray 你返回一个结果数组的承诺,然后然后那个在调用网站上 - 这已添加了知道函数执行异步I / O的调用者的好处。 JavaScript中的编码并发性基于此 - 您可能希望阅读这个问题获得更广泛的想法:

Instead of returning a resultsArray you return a promise for a results array and then then that on the call site - this has the added benefit of the caller knowing the function is performing asynchronous I/O. Coding concurrency in JavaScript is based on that - you might want to read this question to get a broader idea:

function resultsByName(name)
{   
    var Card = Parse.Object.extend("Card");
    var query = new Parse.Query(Card);
    query.equalTo("name", name.toString());

    var resultsArray = [];

    return query.find({});                           

}

// later
resultsByName("Some Name").then(function(results){
    // access results here by chaining to the returned promise
});

您可以在 Parse自己的博客文章

这篇关于在返回函数变量之前,如何等待承诺完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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