Node.js / Express:中间件内部的异步函数?

时间:2018-10-07 14:45:20

标签: node.js express middleware

我想知道您如何使异步函数在中间件中工作?通常,该功能前面的 #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

1 个答案:

答案 0 :(得分:5)

await等待承诺。从test函数返回的承诺将立即得到解决。除了与asyncsetTimeout链接的诺言外,await函数不应知道return在其中发生的任何异步过程。

如果打算延迟,则应为:

async function test(){
    await new Promise(resolve => setTimeout(resolve, 2000));
    console.log('1')
}