使全局对象在内部可用于循环Node.js 10 Google Cloud Function

问题描述

我拥有此Google Cloud Function,对于该示例,我已删除了一些无用的部分。

我想要在for循环内的 const setDeviceConfig 中提供 app.cloudRegion app.projectId 等。

我的猜测是我在某处缺少一些粗箭头,但不确定在哪里。

exports.newFirmware = async (file) => {
    var app = {};
    const str = file.name;
    const bucketName = file.bucket;
    const binaryName = str.substring(0,str.length - 4);
    app.cloudRegion = '1';
    app.projectId = '2';
    app.registryId = '3';
    app.iotClient = new app.iot.v1.DeviceManagerClient({});
    app.parentName = app.iotClient.registryPath(app.projectId,cloudRegion,app.registryId);
    try {
        const responses = await app.iotClient.listDevices({
            parent: app.parentName
        });
        const devices = responses[0];
        for (let i = 0; i < devices.length; i++) {
            const setDeviceConfig = (app.iotClient,bla,app.registryId,app.projectId,app.cloudRegion,bla) => {
                const formattedname = iotClient.devicePath(projectId,registryId,deviceid);               
                const binaryData = Buffer.from(data).toString('base64');
    
                try {
                    const responses = await iotClient.modifyCloudToDeviceConfig(request);                    
                } catch (err) {                   
                    ....
                }
            };
        }
    } catch (err) {
        ....
    }
};

编辑:

    try {
    const responses = await app.iotClient.listDevices({
        parent: app.parentName
    });       
    const devices = responses[0];
    console.log(app.data);  
    for (let i = 0; i < devices.length; i++) {            
        const device = devices[i];
        console.log(device.id);
        setDeviceConfig(app.iotClient,device.id,app.data,binaryName)
    }
            const setDeviceConfig = async (iotClient,deviceid,projectId,data,version) => {               
            const formattedname = iotClient.devicePath(projectId,deviceid);
            console.log('formattedname --> ' + formattedname)
            const binaryData = Buffer.from(data).toString('base64');
            const request = {
                name: formattedname,versionToUpdate: version,binaryData: binaryData,};
            try {
                const responses = await iotClient.modifyCloudToDeviceConfig(request);
                console.log('Success:',responses[0]);
            } catch (err) {
                console.error('Could not update config:',deviceid);
                console.error('Message:',err);
            }               
        };
} catch (err) {
    console.error('Could not list devices',err);
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)