Nodejs,如何在返回Promise的异步迭代之间延迟执行



我有以下函数,它必须在所有通知发送成功/失败后返回Promise

sendNotifications : function(notificationArray, successCallback, stats){
return notificationArray.reduce((acc, x)=>{
return Promise.all([
notificationUtil.sendNotification(x)
.then(
function() {
successCallback(x);
}
)
.catch(e=>{
//handle failure...
}),
new Promise(resolve => setTimeout(resolve, 1000))//Was thinking it will delay the sendNotification calls but it hasn't.
])
}, Promise.resolve());
},

这里是notificationUtil.sendNotification(x)方法:

sendEmail: sendNotification (options) {
return new Promise(function(resolve,reject){
someNPM.sendNotification(function(data) {
if(!data.error_code && !data.is_error)
resolve(true);
else
{
reject(false);
console.error("ERROR: " + data.message);
}
},
options);
});
}

函数someNPM.sendNotification来自一个外部NPM,它不返回Promise,因此,我承诺了它。

问题是,我预计notificationUtil.sendNotification(x)调用之间会有1000ms的延迟,但事实并非如此,sendNotification(x)会在notificationArray的所有元素上立即调用

有人能发现问题吗?

编辑:需要明确的是,我的要求是在通知之间等待1000ms

一个可能的实现。我没有检查这个代码,但它应该会给出一个想法。

function timeout(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
sendNotifications : async function (notificationArray, successCallback, stats){
const length = notificationArray.length;
const promises = [];
for(let i = 0; i < length; i++) {
promises.push(notificationUtil.sendNotification(notificationArray[i]));
await timeout(3000);
}
await Promise.all(promises);
};

最新更新