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

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

问题描述

我仍在为承诺而苦苦挣扎,但由于这里的社区,我取得了一些进展.

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

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

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.

我需要做什么才能让这个函数等待promise的结果?

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,而是返回一个结果数组的 promise,然后 then 在调用站点 - 这具有调用者知道函数正在执行异步 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
});

您可以在 解析自己的博客文章.

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

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