Node.js 6.11.0中ES6 Promise偶尔无法解析的问题求助
Hey there! Let's walk through a robust way to handle your device data processing and storage workflow using Node.js 6.11.0, the node-postgres library, and ES6 Promises to ensure proper sequencing of operations.
1. Core Workflow Overview
Your goal is to:
- Receive periodic data from a device
- Process the data
- Store it in the database (waiting for this to complete before moving on)
- Run subsequent operations once storage is confirmed
Since Node.js 6.11.0 fully supports ES6 Promises, we'll wrap our database operations in Promises to leverage the .then() chain for sequential execution.
2. Complete Code Example
First, make sure you've installed a node-postgres version compatible with Node.js 6.11.0:
npm install pg@6.x
Here's a practical implementation tailored to your needs:
const { Client } = require('pg'); // Initialize PostgreSQL client (update config to match your database setup) const dbClient = new Client({ user: 'your_db_user', host: 'your_db_host', database: 'your_db_name', password: 'your_db_password', port: 5432, }); // Connect to the database once at app startup dbClient.connect() .then(() => console.log('Connected to PostgreSQL successfully')) .catch(err => console.error('Database connection error:', err)); // Function to process incoming raw data function processData(rawData) { return new Promise((resolve, reject) => { try { // Example processing: parse, validate, transform data const processedData = { device_id: rawData.deviceId, reading_value: rawData.sensorReading, recorded_at: new Date().toISOString() }; resolve(processedData); } catch (err) { reject(new Error(`Data processing failed: ${err.message}`)); } }); } // Function to store processed data in the database (wrapped in Promise) function storeData(processedData) { const insertQuery = ` INSERT INTO device_readings (device_id, reading_value, recorded_at) VALUES ($1, $2, $3) RETURNING *; `; const queryValues = [processedData.device_id, processedData.reading_value, processedData.recorded_at]; return new Promise((resolve, reject) => { dbClient.query(insertQuery, queryValues, (err, result) => { if (err) { reject(new Error(`Database storage failed: ${err.message}`)); } else { resolve(result.rows[0]); // Resolve with the inserted record details } }); }); } // Main handler for incoming device data function handleIncomingData(rawDeviceData) { processData(rawDeviceData) .then(processedData => storeData(processedData)) .then(storedRecord => { console.log('Data stored successfully:', storedRecord); // Execute your post-storage operations here doSomethingElse(storedRecord); generateDeviceReport(storedRecord.device_id); }) .catch(err => { console.error('Workflow failed:', err); // Add error recovery logic (e.g., retry, alert, log to monitoring) }); } // Example post-storage operations function doSomethingElse(record) { // e.g., send a webhook notification, update a cache console.log(`Triggering post-storage action for record ID ${record.id}`); } function generateDeviceReport(deviceId) { // e.g., aggregate recent readings, sync with another service console.log(`Generating daily report for device ${deviceId}`); } // Simulate periodic device data (replace with your actual data source) setInterval(() => { const mockData = { deviceId: 'temp_sensor_007', sensorReading: Math.floor(Math.random() * 50) + 10 // Random temp between 10-60 }; handleIncomingData(mockData); }, 60000); // Simulate data every minute
3. Key Notes for Node.js 6.11.0
- Promise Compatibility: Node.js 6.11.0 has full native ES6 Promise support, so no polyfills are needed for basic usage.
- node-postgres Version: Stick to
pg@6.x—newer versions drop support for Node.js 6.x. - Error Handling: Never skip the
.catch()at the end of your Promise chain—unhandled rejections can crash older Node.js processes. - Connection Efficiency: We connect to the database once at startup instead of creating a new connection per request, which reduces overhead.
内容的提问来源于stack exchange,提问作者vrajau
相关产品推荐
相关产品推荐

