如何在for循环中返回数组作为promise? [英] How to return array in for loop as promise?

查看:412
本文介绍了如何在for循环中返回数组作为promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将数组作为可以在函数中调用的promise返回。但它会在调用完成之前返回。请帮帮我怎么办呢?



我尝试过:



I am trying to return the array as a promise which can be called in a function. But it returns before the call completes. Please help me how can I do that?

What I have tried:

function getNewAddedSchedules() {
    var newScheduleArray = [];
    return localforage.getItem("schedulesOffline")
        .then(function (value) {
            for (var i = 0; i < value.length; i++) {
                 ScheduleApi.schedule("57cd27fa390feec82e3be851")
                    .then(function (data) {
                        if (data === "") {
                            newScheduleArray.push(value[i]);
                        }
                    });
            }
            return newScheduleArray;
        });
};


function saveOfflineToOnline() {
    getNewAddedSchedules().then(function (data) {
        console.log(data);
    });
}

推荐答案





您正在尝试在循环中进行多个异步调用。但是你要返回一个承诺,这会导致这个问题。相反,您可以使用
Hi,

You are trying to make multiple async calls within a loop. But you are returning a single promise, which is causing this issue. Instead, you can utilize


q.all来解决此问题。这是一个例子 -



JS Bin - Collaborative JavaScript调试 [ ^ ]



注意aysnc调用函数如何返回一个promise和处理函数应该将它推送到promise数组中。



如果您有任何问题,请告诉我。



谢谢。
q.all to resolve this issue. Here's an example -

JS Bin - Collaborative JavaScript Debugging[^]

Notice how aysnc call function should return a promise and handling function should push it in a promise array.

Let me know if you any questions.

Thanks.


这篇关于如何在for循环中返回数组作为promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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