我有一個用于將一些文本寫入云存盤桶的流。完成后,我希望將一條訊息回傳給父函式。
我嘗試回傳緩沖區流,但這給了我整個緩沖區流物件。我只是想回傳訊息。
例如,如果我有另一個呼叫 toBucket 的函式,我希望回傳檔案已上傳的訊息,以便我可以在瀏覽器中顯示它。
我怎樣才能解決這個問題?
const toBucket = (message, filename) => {
const storage = new Storage();
// Initiate the source
const bufferStream = new stream.PassThrough();
// Write your buffer
bufferStream.end(Buffer.from(message));
const myBucket = storage.bucket(process.env.BUCKET);
const file = myBucket.file(filename);
// Pipe the 'bufferStream' into a 'file.createWriteStream' method.
bufferStream
.pipe(
file.createWriteStream({
validation: 'md5',
})
)
.on('error', (err) => {
// eslint-disable-next-line no-console
console.error(err);
})
.on('finish', () => {
// The file upload is complete.
const message = `${filename} is uploaded!`;
// eslint-disable-next-line no-console
console.log(message);
return message;
});
};
用于
() => async {
await things happening...
const saved = toBucket(message,filename);
sendToBrowser(saved);
}
uj5u.com熱心網友回復:
該toBucket函式應該回傳一個承諾,然后你可以await在你的父函式中。要做到這一點,只需將邏輯包裝toBucket到一個承諾中
const toBucket = (message, filename) => {
return new Promise((resolve, reject) => { // return a promise
const storage = new Storage();
// Initiate the source
const bufferStream = new stream.PassThrough();
// Write your buffer
bufferStream.end(Buffer.from(message));
const myBucket = storage.bucket(process.env.BUCKET);
const file = myBucket.file(filename);
// Pipe the 'bufferStream' into a 'file.createWriteStream' method.
bufferStream
.pipe(
file.createWriteStream({
validation: 'md5',
})
)
.on('error', (err) => {
// eslint-disable-next-line no-console
console.error(err);
reject(err); // reject when something went wrong
})
.on('finish', () => {
// The file upload is complete.
const message = `${filename} is uploaded!`;
// eslint-disable-next-line no-console
console.log(message);
// return message;
resolve(message); // return message and finish
});
})
};
在父函式中:
() => async {
await things happening...
const saved = await toBucket(message,filename); // await
sendToBrowser(saved);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/430578.html
標籤:javascript 异步 异步等待
上一篇:jQueryAjax后臺行程
