如何通过管道将流传输到异步函数并等待响应

时间:2020-02-25 09:54:31

标签: node.js

我有一个异步功能,该功能将某些内容上传到s3。我想将流传输到该异步函数并等待响应。

var table = document.getElementById('tableBody');
var tableData = new Array();

db.collection("Emergency_Feeds").orderBy("timestamp", "desc").onSnapshot(function (querySnapshot) {

  querySnapshot.docChanges().forEach(function (change) {

    console.log('documents retrieved successfully');
    console.log(`is here: ${change.doc.id} => ${change.doc.data().name}`);

    var documentId = change.doc.id;
    var username = change.doc.data().name;
    var emTitle = change.doc.data().title;
    var emDets = change.doc.data().details;
    var emTimeDate = change.doc.data().timestamp.toDate();

    if (change.type === "added") {
      tableData.push(
        [
          documentId,
          emTimeDate,
          emTitle,
          emDets,
          username
      ]);

    }

    if (change.type === "modified") {
        //..... 
        //Here update the table element
        // Note that the DocumentChange contains the old and new index
    }

    if (change.type === "removed") {
        //..... 
        //Here remove the table element
    }
  });

  $('#mydatatable').DataTable({
      retrieve: true,
      data: tableData
  });

});

但是我从未收到回复。

const stream = fs.createReadStream(process.cwd() + "/test/resources/" + "id/front.jpg");

const response = stream.pipe(await storageModule.upload(key, stream));

expect(response.Location).to.equal(`${s3Url}/${key}`)

1 个答案:

答案 0 :(得分:0)

您可以像这样通过传递流并从您的函数中承诺,并等待诺言

function upload(key) {

  const pass = new PassThrough();

  const params = {
      Bucket: "somebucket",
      Key: key,
      Body: pass
  }
  return {
    writeStream: pass,
    promise: s3.upload(params).promise(),
  };

}
const stream = fs.createReadStream(process.cwd() + "/" + "somekey.png");
const {writeStream, promise} = upload("somekey.png");
stream.pipe(writeStream);
const response = await promise;
console.log(response);