lambda.invoke 是否需要 promise 包装器?

Rod*_*Rod 1 javascript amazon-web-services node.js promise aws-lambda

我有以下Promise.all示例。

承诺包装器是否需要lambda.invoke

引用了这个线程

function get1(id) {
    return new Promise((resolve, reject) => {
        const params = {
            FunctionName: 'myLambda', // the lambda function we are going to invoke
            InvocationType: 'RequestResponse',
            Payload: { id },
        };

        lambda.invoke(params, (err, data) => {
            if (err) {
                reject(new Error('error'));
            } else {
                const result = JSON.parse(data.Payload);
                resolve(result);
            }
        });
    }).catch(e => Promise.resolve({ error: 'Error has occurred.' }));
}

exports.getDetails = list => Promise.all(list.map(get1))
    .then((response) => {
        return result;
    }).catch((error) => {
        console.log('oops ', error);
    });
Run Code Online (Sandbox Code Playgroud)

Pat*_*rts 6

lambda.invoke()有一个回调签名,这通常意味着你需要将它包装在一个承诺中,但如果你仔细观察,你会发现它返回一个AWS.Request对象,其中包含一个promise()方法。它还记录了

如果未提供回调,则必须调用AWS.Request.send()返回的请求对象以启动请求。

而对于AWS.Request.promise()

发送请求并返回“thenable”承诺。

所以你的结果get1(id)看起来像:

function get1(id) {
    const params = {
        FunctionName: 'myLambda', // the lambda function we are going to invoke
        InvocationType: 'RequestResponse',
        Payload: { id },
    };

    return lambda.invoke(params).promise().then(({ Payload }) => JSON.parse(Payload));
}
Run Code Online (Sandbox Code Playgroud)