You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

云存储Stream上传完成后如何向父函数返回指定消息而非Stream对象?

Solution: Return a Promise to Wait for Upload Completion

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, and reject() to forward any errors.
  • Await the Call: Using await pauses 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/catch block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 13:12:29