异步函数没有返回响应。

huangapple go评论63阅读模式
英文:

Async function does not return a response

问题

以下是翻译好的部分:

我是新手学习`Javascript`。我正在尝试读取一些文件并构造一个`JSON`对象响应。我能够运行整个代码,但还有一个最后的问题,我没有从`async`函数中获取到响应。

```lang-js
const path = require('path')
const fs = require('fs/promises');

const getProductDetailByProductID = async (id) => {
	const productsFile = path.join(__dirname, 'turing_tasks', 'products.json')
	const customersFile = path.join(__dirname, 'turing_tasks', 'customers.json')
	const reviewsFile = path.join(__dirname, 'turing_tasks', 'reviews.json')
	const imagesFile = path.join(__dirname, 'turing_tasks', 'images.json')

	const { products } = JSON.parse(await fs.readFile(productsFile, 'utf-8'))
	const product = products.filter(product => product.id === id)[0]

	const {reviews} = JSON.parse(await fs.readFile(reviewsFile, 'utf-8'))
	const {customers} = JSON.parse(await fs.readFile(customersFile, 'utf-8'))
	const {images} = JSON.parse(await fs.readFile(imagesFile, 'utf-8'))

	const reviewsData = []
	reviews.forEach((review) => {
		customer = customers.filter(customer => customer.id === review.customer_id)
		if(customer) customer = customer[0]
		const reviewImages = images.filter(image => review.images.includes(image.id))

		reviewsData.push({
			"id": review.id, 
			"rating": review.rating,
			"customer": customer,
			"images": reviewImages
		})
	})

	return {
		"id": product.id,
		"name": product.name,
		"reviews": reviewsData
	}
}
(async () => {
  const result = await getProductDetailByProductID(1);
  return result
})();  // 这里没有获取到任何内容

我正在使用以下命令运行此文件

nodemon task.js

另外,如果这段代码写得不够好,也请推荐更好的写法。如果可能的话,请分享相关链接。


<details>
<summary>英文:</summary>

I am new to `Javascript`. I am trying to read a few files and construct a `JSON` object response. I am able to run the entire code, however, one last piece is remaining, I am not getting a response from the `async` function.

```lang-js
const path = require(&#39;path&#39;)
const fs = require(&#39;fs/promises&#39;);

const getProductDetailByProductID = async (id) =&gt; {
	const productsFile = path.join(__dirname, &#39;turing_tasks&#39;, &#39;products.json&#39;)
	const customersFile = path.join(__dirname, &#39;turing_tasks&#39;, &#39;customers.json&#39;)
	const reviewsFile = path.join(__dirname, &#39;turing_tasks&#39;, &#39;reviews.json&#39;)
	const imagesFile = path.join(__dirname, &#39;turing_tasks&#39;, &#39;images.json&#39;)

	const { products } = JSON.parse(await fs.readFile(productsFile, &#39;utf-8&#39;))
	const product = products.filter(product =&gt; product.id === id)[0]

	const {reviews} = JSON.parse(await fs.readFile(reviewsFile, &#39;utf-8&#39;))
	const {customers} = JSON.parse(await fs.readFile(customersFile, &#39;utf-8&#39;))
	const {images} = JSON.parse(await fs.readFile(imagesFile, &#39;utf-8&#39;))

	const reviewsData = []
	reviews.forEach((review) =&gt; {
		customer = customers.filter(customer =&gt; customer.id === review.customer_id)
		if(customer) customer = customer[0]
		const reviewImages = images.filter(image =&gt; review.images.includes(image.id))

		reviewsData.push({
			&quot;id&quot;: review.id, 
			&quot;rating&quot;: review.rating,
			&quot;customer&quot;: customer,
			&quot;images&quot;: reviewImages
		})
	})

	return {
					&quot;id&quot;: product.id,
					&quot;name&quot;: product.name,
					&quot;reviews&quot;: reviewsData
				}
}
(async () =&gt; {
  const result = await getProductDetailByProductID(1);
  return result
})();  // This does not fetch anything

I am running this file using below command

nodemon task.js

Also, please recommend a better way of writing this code if it is poorly written. Please share a link for the same.

答案1

得分: 0

因为您的getProductDetailByProductID是异步的,您应该像这样调用它:

(async () => {
  const result = await getProductDetailByProductID(1);
  console.log(result);
})();

更多信息:

getProductDetailByProductID // 此函数是异步的,并返回一个Promise值

如果您想要获取值:

async function ss() {
  const result = await getProductDetailByProductID(1);
  console.log(result); // 您的`getProductDetailByProductID`的返回值
  return result;
}
ss()

如果您仍然要从异步函数中返回值,还需要使用async/await来获取值:

async function s2() {
  const result = await ss();
  console.log(result);
}
英文:

because your getProductDetailByProductID is async, you should call your getProductDetailByProductID like this:

(async () =&gt; {
  const result = await getProductDetailByProductID(1);
  console.log(result);
})();

more:

getProductDetailByProductID // this function is async and return a Promise value

if you want get the value:

function ss ()  {
  const result = await getProductDetailByProductID(1);
  console.log(result); // your getProductDetailByProductID&#39;s return value
  return result;
}
ss()

if you still return value from async function, also need use async await to get value

sync function s2() {
  const result = await ss();
  console.log(result);
}

huangapple
  • 本文由 发表于 2023年7月18日 14:59:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定