NodeJS 获取对象意外执行

c86crjj0  于 2023-02-08  发布在  Node.js
关注(0)|答案(1)|浏览(93)

我正在使用node,我有一个api设置为netlify无服务器函数,这样我就可以并行运行多个进程。
作为其中的一部分,我想创建一个未执行的fetch对象承诺数组,然后我可以使用类似下面的命令在paralell中执行该数组:

const responses = await Promise.allSettled(promiseArray);

到目前为止我有:

for (let i = 0; i < groupedRecords.length; i++) {
  const groupedRecord = groupedRecords[i];
  const fetchObjects = await createFetchObjectArray(groupedRecord);

}

async function createFetchObjectArray(records) {

  const fetchURL = (obj) => fetch('http://localhost:8888/.netlify/functions/meta1', {
  method: 'POST',
  body: JSON.stringify(obj),
  headers: { 'Content-Type': 'application/json' }
  });

 let outputArray = [];
 for (let i = 0; i < (records.length); i++) {
    const record = await records.pop();
    const obj = { "_id": record._id };
    const fetchObj = fetchURL(obj);
    outputArray.push(fetchObj);

  }

  return outputArray;

}

我希望得到一个数组的承诺到'fetchObjects',但他们似乎试图执行。我看到:

FetchError: request to http://localhost:8888/.netlify/functions/meta1 failed, reason: connect ECONNREFUSED 127.0.0.1:8888

我如何阻止fetch对象的执行?

1l5u6lss

1l5u6lss1#

调用fetchURL将立即执行它。awaitPromise.allSettled不是 start 异步操作的机制,它们是等待已经启动的操作的机制。
如果要生成函数数组并且不立即调用它们,请使用:

const fetchObj = fetchURL(obj);
outputArray.push(fetchObj);

您可能只想:

outputArray.push(() => fetchURL(obj));

如果您以后想使用Promise.allSettled,您可以这样做:

Promise.allSettled(outputArray.map(foo => foo());

下面是代码的清理版本,它还修复了更多的bug:

for(const groupedRecord of groupedRecords) {
  const fetchObjects = createFetchObjectArray(groupedRecord);
  // Assuming you're doing something with fetchObjects after?
}

function fetchURL(obj) {
  return fetch('http://localhost:8888/.netlify/functions/meta1', {
    method: 'POST',
    body: JSON.stringify(obj),
    headers: { 'Content-Type': 'application/json' }
  });
}

function createFetchObjectArray(records) {

  return records.map(record => {
    const obj = { "_id": record._id };
    return () => fetchURL(obj);
  });

}

相关问题