垃圾邮件的相同输入有时会在早期拒绝时通过

时间:2017-10-21 21:51:54

标签: node.js promise

function createWallet(network, walletToken, deviceToken) {
return new Promise((resolve, reject) => {

    findWalletByWalletToken(network, walletToken)
    .then((docs) => {
        if (docs.length !== 0) {    
            for (var i in docs) {
                if (docs[i].curDeviceToken == deviceToken || docs[i].walletToken.indexOf(walletToken) !== -1){
                    reject(new Error("walletToken already exists"));
                    return
                }
            }

        }
        console.log(docs)
    })
    .catch((err) => {
        console.log(err);
    })

    findDeviceByDeviceToken(network, deviceToken)
    .then((docs) => {
        resolve(docs);
    })
})
.then((docs) => {
          // Adds a wallet
     }

日志看起来像这样

Docs in WalletTokenSearch[object Object],[object Object]
Docs in WalletTokenSearch[object Object],[object Object]
Docs in WalletTokenSearch[object Object],[object Object]
Docs in WalletTokenSearch[object Object],[object Object]
Docs in WalletTokenSearch[object Object],[object Object]
Docs in WalletTokenSearch[object Object],[object Object]
Docs in WalletTokenSearch[object Object],[object Object]
[Hail][DB] Inserted new wallet
Docs in WalletTokenSearch[object Object],[object Object]

Docs in WalletTokenSearch[object Object],[object Object]findWalletByWalletToken

中的打印声明

问题是我会多次点击端点,然后每次都会通过代码传递相同的输入并添加到数据库中创建重复...您可以反复执行此操作并添加数千个以这种方式重复

1 个答案:

答案 0 :(得分:2)

无论如何,您总是同时拨打findWalletByWalletTokenfindDeviceByDeviceToken。如果后者首先完成,或者前者没有拒绝承诺,您的承诺就会得到满足。这是最好的竞争条件。

请注意,无论结果如何,都会执行这两个操作。我不认为这就是你想要的。

function createWallet(network, walletToken, deviceToken) {
    return findWalletByWalletToken(network, walletToken).then(docs => {
        for (var i=0; i<docs.length; i++) {
            if (docs[i].curDeviceToken == deviceToken || docs[i].walletToken.indexOf(walletToken) !== -1){
                throw new Error("walletToken already exists");
            }
        }
        console.log(docs)
        // only call this here:
        return findDeviceByDeviceToken(network, deviceToken);
    }).then((docs) => {
        // Adds a wallet
    });
}