gpt4 book ai didi

Javascript 将 Promise 推送到数组中

转载 作者:行者123 更新时间:2023-12-01 15:14:37 25 4
gpt4 key购买 nike

我正在尝试创建一组 promise 并使用 Promise.all 调用它们.

我在将函数正确插入数组时遇到问题,似乎它们被调用而不是被插入并等待 Promise.all() .

function findSpecialAbility(players, gameId, message) {
return new Promise(function(resolve, reject) {
let playersWithSpecials = _.reject(players, function(p) {
return p.role === 'alphaWolf' ||
p.role === 'betaWolf' ||
p.role === 'villager' ||
p.role === 'alchemist' ||
p.targetId === 0 ||
p.abilityUsed === true;
});
if (playersWithSpecials.length === 0) {
resolve();
} else {
let specialsToUse = [];
for (let i = 0, j = playersWithSpecials.length; i < j; i++) {
specialsToUse.push(useSpecialAbility(playersWithSpecials[i], gameId, message, players));
}
//Promise.all(specialsToUse).then(r = > console.log(r));
}
});
}


// Using promise below because some of the role will have database updates.
function useSpecialAbility(playerData, gameId, message, players) {
return new Promise(function(resolve, reject) {
if (playerData.role === 'seer') {
let getTargetData = _.find(players, {
id: playerData.targetId
});
message.guild.members.get(playerData.id).send(`Your target is a ${getTargetData.role}!`);
resolve('foo');
}
});
}

最佳答案

it seems they are being called instead of inserted and wait for Promise.all()



当您调用 Promise.all 时,您似乎希望 Promise 中的代码同时运行.

如果这是您想要的,那么在 Promise 中包装代码可能不是您想要的。

相反,您需要将稍后要运行的代码包装在一个普通的 ole 函数中。您可以将这些函数添加到数组中,然后在循环中调用每个函数。从您的代码的外观来看,您可能甚至不需要 promise 。

请参见下面的示例:

// this function returns another function `runnable` and can be called later (synchronously) to get the result
function runLater (index) {
return function runnable() {
console.log(`this code is ran later. from ${index}`);
return `from ${index}`;
}
}

console.log('this is run now');

const tasks = [];

for (let i = 0; i < 3; i += 1) {
tasks.push(runLater(i));
}

console.log('this is run');


// use Array.prototype.map to map the array of functions to what they return by invoking each one.
const valuesOfTasks = tasks.map(task => task());
console.log({valuesOfTasks});

console.log('this is run after');



只有在处理异步控制流时才需要 Promise。延迟执行可以同步完成,只需将一段代码包装在一个函数中。当您想执行该代码时,只需调用该函数。

编辑:

I need to wait for all the useSpecialAbility to be done before moving on with my code. Some of them will write/read from the database, that's why I used promises.



在这种情况下,您将不得不使用 Promise.all但是,如果您希望它们同时运行,您仍然需要将这些 promise 包装在不带参数的函数中。

Promise 的代码块实际上是同步运行的(与调用 .thenPromise.all 时运行 block 相比),所以如果你仍然希望 Promise 稍后运行,你仍然可以将它们包装在函数中。

看这个例子:

function waitThenSay(milliseconds, message) {
return new Promise(resolve => {
console.log(`waiting to say: "${message}"...`)
setTimeout(() => {
// log to console for immediate side-effect
console.log(message.toUpperCase() + '!');
// also resolve with the message
resolve(message);
}, milliseconds);
});
}

console.log('this is run first');

// tasks is an array of functions that return promises
const tasks = [];
for (let i = 1; i <= 3; i += 1) {
tasks.push(() => waitThenSay(i * 2000, `hello from task ${i}`));
}

console.log('this is run second');

// execute the tasks by mapping each function to their invocation
const arrayOfPromises = tasks.map(task => task())

// call Promise.all on that array
Promise.all(arrayOfPromises).then(result => {
console.log({result});
});


希望这可以帮助!

关于Javascript 将 Promise 推送到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47134644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com