node.js - 在 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中结束了连接。
我看过这个,这就是我尝试过的,但是我不确定我是否理解发生了什么。
解决方案
推荐阅读
- css - 如何根据背景反转笔触文本颜色
- cryptography - 已知 N(私钥)时如何在 ECC 中执行快捷方式功能
- c# - 如何修复此代码中的“要解密的数据长度无效”
- javascript - 'empty x 2' 数组和 [undefined, undefined] 有什么区别?
- java - 在 Apache Spark 中解析 JSON 时出现奇怪的错误
- protocol-buffers - protobuf 中的随机字段编号
- python - 如何将列表函数应用于pandas df中的文本生成器obj
- c - 如何修复 ld:警告:忽略文件 Atome 错误?
- java - 不同情况下单相等
- angular - 错误:找不到元素 [#map_canvas]