简体   繁体   English

Promise.resolve()返回使用Array.push()填充的空数组

[英]Promise.resolve() returns empty arrays that were populated using Array.push()

I have this code in which I add users to the Firebase DB, and resolve the Promise when the user import is done. 我有此代码,可以在其中添加用户到Firebase数据库,并在完成用户导入后resolve Promise In the resolve, I include arrays which contain the users that were added. 在解决方案中,我包括包含所添加用户的数组。 These arrays are populated when a single user is added. 添加单个用户时,将填充这些数组。 The code is below: 代码如下:

return new Promise((resolve, reject) => {
    let usersAdded = [];
    users.map((user, index) => {
        db.ref('/users').push(user, err => {
            if(!err) {
                usersAdded.push(user)
                console.log(`Array at iteration ${index}: ${usersAdded}`)
            }
            if(index == users.length-1){
              resolve({status: true, usersAdded})
            }
        })
    })
})

Console Output: 控制台输出:

Array at iteration 0: [{name: nadir, email: iamnadir10@yahoo.com, creditCard: true}]
Array at iteration 1: [{name: nadir, email: iamnadir10@yahoo.com, creditCard: true}, {name: arslan, email: arslan346@yahoo.com, creditCard: true}]
Array at iteration 2: [{name: nadir, email: iamnadir10@yahoo.com, creditCard: true}, {name: arslan, email: arslan346@yahoo.com, creditCard: true}, {name: farhan, email: farhan1992@gmail.com, creditCard: true}]

Although when I see the response on .then(user) , it returns an empty array ( usersAdded ). 尽管当我在.then(user)上看到响应时,它返回一个空数组( usersAdded )。 Users get added in Firebase as well. 用户也会被添加到Firebase中。 Can anyone tell me what is the problem here? 谁能告诉我这里是什么问题?

Edit: 编辑:

I was able to solve it, the problem was that the Promise was resolved before the db.ref.push triggered the callback, in that callback, I was populating the array, as it was an async operation. 我能够解决它,问题是Promise在db.ref.push触发回调之前已解决,在该回调中,我正在填充数组,因为它是异步操作。

Like CertainPerformance said in the comments your code only works assuming the push callbacks get called in order. 就像在评论中的SomePerformance所说,您的代码仅在假定顺序调用push回调的情况下才有效。 Since they are most likely asynchronous the order of the callback execution is not guaranteed. 由于它们很可能是异步的,因此无法保证回调执行的顺序。 This means if the last push callback is called first you promise already resolves. 这意味着,如果最先调用最后一个推送回调,则您保证已经解决。 For this reason you should use Promise.all() to wait until all the push callbacks are resolved then handle the results. 出于这个原因,您应该使用Promise.all()等到所有推式回调都解决后再处理结果。

return Promise.all(users.map(user => {
    return new Promise(resolve => db.ref('/users').push(user, resolve));
}))
.then(pushResults => { // all push callbacks are resolved
    return pushResults
        .map((error, index) => error ? null : users[index])
        .filter(Boolean);
});

You might however want to call reject if none of the users successfully saved. 但是,如果没有一个用户成功保存,则可能要调用拒绝 This makes the code more complicated, but you can than use catch on the returned promise if no users where saved. 这使代码更加复杂,但是如果没有用户保存,则可以比对返回的诺言使用catch

// return a resolved promise if the users array is empty
if (!users.length) return Promise.resolve(users);

// handle a non-empty users array
return Promise.all(users.map(user => {
    return new Promise(resolve => db.ref('/users').push(user, resolve));
}))
.then(pushResults => {
    // all users had errors
    if (pushResults.every(Boolean)) 
        return Promise.reject(pushResults);

    // one or multiple users had no errors
    return pushResults
        .map((error, index) => error ? null : users[index])
        .filter(Boolean);
});

Returning a value other than a promise inside a then function will simply be forwarded to the next then as if you returned Promise.resolve(value) . then函数中返回promise以外的值将被简单地转发到下一个then ,就像您返回Promise.resolve(value)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM