我想知道您如何使异步函数在中间件中工作?通常,该功能前面的 #define signalToRelayPin 12
#define sensorPin 7
int lastSoundValue;
int soundValue;
long lastNoiseTime = 0;
long currentNoiseTime = 0;
long lastLightChange = 0;
int relayStatus = HIGH;
int clap_interval = 500;
int claps = 0;
void setup() {
pinMode(sensorPin, INPUT);
pinMode(signalToRelayPin, OUTPUT);
Serial.begin(115200);
}
struct DataBlockStruct meting1,meting2;
void loop() {
soundValue = digitalRead(sensorPin);
currentNoiseTime = millis();
if (soundValue == 1 && lastSoundValue == 0)
{
if (claps == 0) // allow first to register without much condition
{
claps = 1;
lastNoiseTime = currentNoiseTime;
}
else
{
if (currentNoiseTime > lastNoiseTime + clap_interval)
{
claps++;
lastNoiseTime = currentNoiseTime;
relayStatus = !relayStatus;
}
}
}
else
{
if (currentNoiseTime > lastNoiseTime + 2 * clap_interval) // no claps for a longer duration time to print and/or reset clap
{
if (claps > 0)
{
Serial.print(claps);
Serial.println(" CLAPS");
claps = 0; ///reset
}
}
}
//lastSoundValue = soundValue;
delay(50); // delay polling
}
可以完成工作,但是在中间件中,它似乎不起作用。
index.js:
await
中间件/bob.js:
const bob= require('../middleware/bob');
router.get('/', [bob(['channel1','channel2','channel3'])], async (req, res) => {
console.log('3')
})
运行此代码时。它将写入控制台:2 3 1
答案 0 :(得分:5)
await
等待承诺。从test
函数返回的承诺将立即得到解决。除了与async
或setTimeout
链接的诺言外,await
函数不应知道return
在其中发生的任何异步过程。
如果打算延迟,则应为:
async function test(){
await new Promise(resolve => setTimeout(resolve, 2000));
console.log('1')
}