NodeJS 在循环后使用 promise 执行函数
NodeJS do function after loop with promise
我有一台服务器有时会脱机并错过一些打开的数据以添加到数据库中。所以我正在制作一个功能,以便在重新上线后到达此事件。
每个事件都必须一个接一个地写。然后它可以听新的。
目前,我确实在 can
中做了一个带有 promise 的“for 循环”
const someProcedure = async events => {
for (let i = 0; i < events.length; i++) {
const x = await new Promise(r => {
web3.eth.getBlock(events[i].blockNumber).then(result => {
console.log(convertEvent(events[i], result.timestamp)); })
.then(r());
})
}
}
someProcedure(events).then(function(result) {
console.log('Loop finished, do...');
//If I add a function here, does it need to be a promise ?
})
"Console.log" 在我的循环中运行良好但不是最后一个"循环完成..."。
我在这里实现了一些示例 ...
不确定为什么 'Loop finished, do...'
没有被记录。
但也许我们可以先尝试整理您的代码。
首先,您有一个 Promise 的 Promise 构造函数,并且您将 thenables 与 async / await 混合..
因此,在执行此操作后,您的代码可能如下所示。
const someProcedure = async events => {
for (let i = 0; i < events.length; i++) {
const result = await web3.eth.getBlock(events[i].blockNumber);
console.log(convertEvent(events[i], result.timestamp));
}
}
someProcedure(events).then(function() {
console.log('Loop finished, do...');
//If I add a function here, does it need to be a promise ?
//^^ No, unless the function is async, but if it is
//it would make sense to return another promise, and probably
//use async / await again to keep things tidy.
})
我有一台服务器有时会脱机并错过一些打开的数据以添加到数据库中。所以我正在制作一个功能,以便在重新上线后到达此事件。 每个事件都必须一个接一个地写。然后它可以听新的。 目前,我确实在 can
中做了一个带有 promise 的“for 循环”const someProcedure = async events => {
for (let i = 0; i < events.length; i++) {
const x = await new Promise(r => {
web3.eth.getBlock(events[i].blockNumber).then(result => {
console.log(convertEvent(events[i], result.timestamp)); })
.then(r());
})
}
}
someProcedure(events).then(function(result) {
console.log('Loop finished, do...');
//If I add a function here, does it need to be a promise ?
})
"Console.log" 在我的循环中运行良好但不是最后一个"循环完成..."。
我在这里实现了一些示例
不确定为什么 'Loop finished, do...'
没有被记录。
但也许我们可以先尝试整理您的代码。 首先,您有一个 Promise 的 Promise 构造函数,并且您将 thenables 与 async / await 混合..
因此,在执行此操作后,您的代码可能如下所示。
const someProcedure = async events => {
for (let i = 0; i < events.length; i++) {
const result = await web3.eth.getBlock(events[i].blockNumber);
console.log(convertEvent(events[i], result.timestamp));
}
}
someProcedure(events).then(function() {
console.log('Loop finished, do...');
//If I add a function here, does it need to be a promise ?
//^^ No, unless the function is async, but if it is
//it would make sense to return another promise, and probably
//use async / await again to keep things tidy.
})