功能仍然执行即使使用setTimeout和promises

时间:2016-05-01 14:51:56

标签: javascript promise settimeout

我试图使用promises等到数据填满之后再触发20秒setTimeout,但setTimeout没有暂停执行该函数。

强制finishedGame()等待20秒的任何建议?

var q1 = "SELECT name, pic, link FROM users where id = " + winner;
connection.query(q1, function (err, results) {
    if (err) throw err;
    return new Promise(function(resolve, reject) {
        var pic = results[0].pic;
        var name = results[0].name;
        var link = results[0].link ;
        var winnerInfo = {
            id: winner,
            name: name,
            total: total,
            totalItems: totalitems,
            pic: pic,
            link: link,
            percentage: playerPercentage
        }
            io.sockets.emit('animation', { 
            winnerData : winnerInfo 
        }); 
        resolve(winnerInfo);
    }).then(function(winnerInfo){
        setTimeout(finishedGame(winner, winnerInfo), 20000);
    });
    connection.end();
});

1 个答案:

答案 0 :(得分:2)

要正确延迟finishedGame()的执行,你应该包装函数调用,而不是调用函数。试试这个:

setTimeout(function () {
 finishedGame(winner, winnerInfo)
}, 20000);