Node.js,如何延迟返回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,因此我对它进行了承诺。

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

有人可以发现问题吗?

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

sja811024 回答:Node.js,如何延迟返回Promise的异步迭代之间的执行

可能的实现。我没有检查这段代码,但是应该给出一个主意。

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);
};
本文链接:https://www.f2er.com/3159644.html

大家都在问