首页 > 解决方案 > 在 end() 之前等待函数

问题描述

编辑:添加了更多代码。

    const express = require('express');
    var bodyParser = require('body-parser');
    const app = express();

    var urlencodedParser = bodyParser.urlencoded({extended: false})

    const {google} = require('googleapis');
    const {PubSub} = require('@google-cloud/pubsub');
    const iot = require('@google-cloud/iot');
    const API_VERSION = 'v1';

    const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
    app.get('/', urlencodedParser, (req, res) => {

    const projectId = req.query.proyecto;
    const cloudRegion = req.query.region;
    const registryId = req.query.registro;
    const numSerie = req.query.numSerie;
    const command = req.query.command;

    const client = new iot.v1.DeviceManagerClient();
    if (client === undefined) {
        console.log('Did not instantiate client.');
    } else {
        console.log('Did instantiate client.');
        sendCom();
    }

    async function sendCom() {
        const formattedName = await client.devicePath(projectId, cloudRegion, registryId, numSerie)
        const binaryData = Buffer.from(command);
        const request = {
            name: formattedName,
            binaryData: binaryData,
        };
        return client.sendCommandToDevice(request).then(responses => res.status(200).send(JSON.stringify({
            data: OK
        }))).catch(err => res.status(404).send('Could not send command. Is the device connected?'));
    }
});

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`);
    console.log('Press Ctrl+C to quit.');
});

module.exports = app;

我有这个功能,我在客户端启动后调用: sendCom();

     async function sendCom() {
        const formattedName = await client.devicePath(projectId, cloudRegion, registryId, deviceId)
        const binaryData = Buffer.from(command);            
        const request = { name: formattedName, binaryData: binaryData, };

        client.sendCommandToDevice(request)
        .then(responses => {
            res.status(200).send(JSON.stringify({ data: OK })).end();                
        })
        .catch(err => {
            res.status(404).send('Could not send command. Is the device connected?').end();             
        });
    }

我的问题是sendCommandToDevice可以完美执行,但是我得到了catch error。据我了解,这是因为在.then中结束了连接。

我看过这个,这就是我尝试过的,但是我不确定我是否理解发生了什么。

标签: node.js

解决方案


你不能使用sendwith end

  • end()当您想要结束请求并且想要在没有数据的情况下响应时使用。

  • send()用于结束请求并响应一些数据。

你可以在这里找到更多关于它的信息。


推荐阅读