在AWS Lambda上解决承诺后,.then不会运行

时间:2019-10-25 14:21:51

标签: javascript amazon-web-services asynchronous aws-lambda es6-promise

代码:

var promiseResolve, promiseReject;    

function iterateRules(rules, params, i = 0) {

    CWevents.putRule(rules[i], function(err, data) {    // This is an async function with a callback
        if (err) console.log(err); promiseReject(err)

        responses++
        params['Lambda_invoke']['SourceArns'].push(data.RuleArn)

        if(responses == rules.length){ promiseResolve("Success"); console.log("Resolved")} 
        // After two responses are confirmed, this if does run and I get the "Resolved"
    })
    i++
    if(i < rules.length){
        setTimeout( function(){
            iterateRules(params['CW_rules']['Rules'], params, i)
        }, 50)
    }
}

new Promise((resolve, reject) => {
    resolve() 
// This part is added solely for the code to make sense, it's taken out of a 
// bigger script and lots of unnecessary data is removed 
})
.then((Item) => {
            return new Promise((resolve, reject) => {
                promiseReject = reject;
                promiseResolve = resolve;
                iterateRules(params['CW_rules']['Rules'], params)
            })
}) .then((res) => {
        console.log("This ran")
   })

iterateRules函数应该多次运行一个异步函数,并解决在获取最后一个响应时调用它的Promise。 if(responses == rules.length)确实按预期运行,并在控制台中记录了“已解决”。一切成功,没有错误。

下面是此代码的上下文,执行了iterateRules函数,但没有执行此后的.then。如果我直接在承诺中放入resolve(),它就会执行。此脚本可能有什么问题?我尝试单独运行它的一个简单版本,如下所示:

var res, rej;

function dude(){
    res()
}

new Promise((resolve, reject) => {
    res = resolve;
    dude()
}).then((dude) => {
    console.log("resolved")
})

它确实有效,所以我很困惑。可能导致问题的原因是什么?预先感谢。

1 个答案:

答案 0 :(得分:1)

我会让iterateRules()返回一个Promise(因为它是异步的)。我还要保证CWevents.putRule()函数的正确性,以便您可以完成以下代码:

function iterateRules(rules, params) {
    return Promise.all(rules.map(rule => {
        return CWevents.putRule(rule)
    })).then((data) => {
        params['Lambda_invoke']['SourceArns'].push(data.RuleArn)
    })
}

然后您的iterateRules处理程序将变为:

iterateRules(rules,params).then(()=>{
    // Do something...
})