云存储Stream上传完成后如何向父函数返回指定消息而非Stream对象?
The core issue here is that your toBucket function runs asynchronous operations (the stream pipe and cloud upload), but it doesn't wait for those operations to finish before returning. The return inside the finish event handler only exits that callback—not the parent toBucket function—so your calling code never gets the success message you want.
To fix this, wrap the entire upload logic in a Promise, which lets you explicitly resolve with your success message once the upload completes, or reject with an error if something goes wrong. Here's how to adjust your code:
Step 1: Rewrite toBucket to Return a Promise
const toBucket = (message, filename) => { return new Promise((resolve, reject) => { const storage = new Storage(); const bufferStream = new stream.PassThrough(); bufferStream.end(Buffer.from(message)); const myBucket = storage.bucket(process.env.BUCKET); const file = myBucket.file(filename); bufferStream .pipe(file.createWriteStream({ validation: 'md5' })) .on('error', (err) => { console.error(err); reject(err); // Pass the error to the promise's reject handler }) .on('finish', () => { const successMessage = `${filename} is uploaded!`; console.log(successMessage); resolve(successMessage); // Pass your success message to the promise's resolve handler }); }); };
Step 2: Await the Promise in Your Calling Code
Since toBucket now returns a Promise, use await when calling it to ensure you get the success message only after the upload finishes (your calling function is already marked as async, so this works seamlessly):
(async () => { await things happening... try { const saved = await toBucket(message, filename); sendToBrowser(saved); // This will now receive "filename is uploaded!" } catch (err) { // Gracefully handle upload failures and notify the browser sendToBrowser(`Upload failed: ${err.message}`); } })();
Key Changes Explained:
- Promise Wrapper: The Promise acts as a container for the async upload process. We use
resolve()to pass the success message once the upload completes, andreject()to forward any errors. - Await the Call: Using
awaitpauses your async function until the Promise resolves, so you don't try to send a message to the browser before the upload is done. - Error Handling: The
try/catchblock lets you handle upload failures cleanly and communicate them to the browser instead of letting errors go unhandled.
This approach ensures you get the exact success message you want returned to the parent function, which you can then pass directly to the browser.
内容的提问来源于stack exchange,提问作者Christoph

