简体   繁体   English

在返回 function 的变量之前,如何等待 promise 完成?

[英]How do I wait for a promise to finish before returning the variable of a function?

I'm still struggling with promises, but making some progress thanks to the community here.我仍在为承诺而苦苦挣扎,但由于这里的社区,我取得了一些进展。

I have a simple JS function which queries a Parse database.我有一个简单的 JS function 查询 Parse 数据库。 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.它应该返回结果数组,但显然由于查询的异步性质(因此承诺),function 在结果之前返回,给我留下一个未定义的数组。

What do I need to do to make this function wait for the result of the promise?我需要做什么才能让这个 function 等待 promise 的结果?

Here's my code:这是我的代码:

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");
               }
    });                           

}

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. 而不是返回的resultsArray你返回一个结果数组一个承诺,然后then上调用点-这已经调用者知道功能的好处是执行异步I / O。 Coding concurrency in JavaScript is based on that - you might want to read this question to get a broader idea: JavaScript中的编码并发性基于此 - 您可能希望阅读此问题以获得更广泛的想法:

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
});

You can see more examples of using parse promises with queries in Parse's own blog post about it . 您可以在Parse自己的博客文章中看到更多使用解析承诺的示例。

What do I need to do to make this function wait for the result of the promise? 我需要做些什么来使这个函数等待承诺的结果?

Use async/await (NOT Part of ECMA6, but available for Chrome, Edge, Firefox and Safari since end of 2017, see canIuse ) 使用async/await (不是ECMA6的一部分,但自2017年底起可用于Chrome,Edge,Firefox和Safari,请参阅canIuse
MDN MDN

    async function waitForPromise() {
        // let result = await any Promise, like:
        let result = await Promise.resolve('this is a sample promise');
    }

Added due to comment: An async function always returns a Promise, and in TypeScript it would look like: 由于评论而添加:异步函数始终返回Promise,在TypeScript中它看起来像:

    async function waitForPromise(): Promise<string> {
        // let result = await any Promise, like:
        let result = await Promise.resolve('this is a sample promise');
    }

You don't want to make the function wait, because JavaScript is intended to be non-blocking. 您不希望使函数等待,因为JavaScript旨在是非阻塞的。 Rather return the promise at the end of the function, then the calling function can use the promise to get the server response. 而是在函数结束时返回promise,然后调用函数可以使用promise来获取服务器响应。

var promise = query.find(); 
return promise; 

//Or return query.find(); 

You're not actually using promises here. 你实际上并没有在这里使用承诺。 Parse lets you use callbacks or promises; Parse允许你使用回调或承诺; your choice. 你的选择。

To use promises, do the following: 要使用promises,请执行以下操作:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. 现在,要在promise完成后执行东西,你可以在then()调用中的promise回调中执行它。 So far this would be exactly the same as regular callbacks. 到目前为止,这与常规回调完全相同。

To actually make good use of promises is when you chain them, like this: 要真正好好利用承诺就是当你把它们链接起来时,就像这样:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

I have same problem, so I maintain some code, code need call ajax done to process another task, here my code 我有同样的问题,所以我维护了一些代码,代码需要调用ajax来处理另一个任务,这里是我的代码

this.bindChangeEvent = function () {
    //select all bind change
    this._select_all.bind('change', function () {
        console.log('All')
        if ($(this).is(":checked")) {
            ///todo: call ajax to get all ids
            var idsAllItem = pointer.getAllData();

            console.log(idsAllItem);
            console.log('Another todo');

Ajax function Ajax功能

this.getAllData = function() {
    var promises = [];
    var def = new $.Deferred();
    return new Promise((resolve, reject) => {
        // AJAX request
        var url = '...';
        $.ajax({
            url: url,
            type: "get",
            async: true,
            data: {},
            dataType: "json",
            success: function (data) {
                console.log('Ajjax done');
                resolve(data)
            },
            error: function (err) {
                reject(err)
            }
        });
    })
};

and i get result 我得到了结果

Another todo
Output
Ajax Done

…. ...。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在从我的 promise / function 返回之前等待 forEach 完成 - How to wait for a forEach to finish before returning from my promise / function 如何在函数返回之前等待promise完成 - How to wait for promise to finish before function returns 如何使循环等待db promise完成,然后再继续下一次迭代? - How do I make for loop wait for db promise to finish before it continues to next iteration? 如何在返回之前等待 mongoose.exec() function 完成? - How to wait for a mongoose .exec() function to finish before returning? 等待函数完成后再返回承诺 - waiting for the the function to finish before returning a promise 如何在开始下一个 function 之前等待我的滚动 function 完成? - How do I wait for my scroll function to finish before starting the next function? 如何在Javascript中执行ABCD功能之前等待所有Promises完成? - How do I wait for all Promises to finish before executuing ABCD function in Javascript? 如何在执行另一个功能之前等待某个功能完成? - How do I wait for a certain function to finish before executing another one? 如何在继续之前等待递归 function 完全完成? - How can I wait for a recursive function to completely finish before continuing? 在继续前进之前,如何等待带有异步调用的.map()完成? - How do I wait for a .map() with asynchronous calls to finish before moving on?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM