Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 异步函数未被识别为异步函数_Node.js_Async Await - Fatal编程技术网

Node.js 异步函数未被识别为异步函数

Node.js 异步函数未被识别为异步函数,node.js,async-await,Node.js,Async Await,我制作了一个从服务器获取数据的函数 const http = require('node-fetch') getProdData = async function(prodNum) { const response = await http(`https://www.xxxxxx.com/api/products/${prodNum}/`) const json = await response.json() console.log(json) return j

我制作了一个从服务器获取数据的函数

const http = require('node-fetch')

getProdData = async function(prodNum) {
    const response = await http(`https://www.xxxxxx.com/api/products/${prodNum}/`)
    const json = await response.json()
    console.log(json)
    return json
}
如果我直接调用它,它将返回一个待定的承诺

const promise = getProdData(12)
console.log(promise) // this returns a {promise:pending} 
当我试图等待时,它会抛出一个错误

const data = await promise 
// this throws [SyntaxError: await is only valid in async function]
console.log(data)
我已经重新研究了类似的案例,它们几乎都是相同的代码,并且正在运行


我可能遗漏了什么吗?

所有
async
函数都会返回一个承诺,并且在函数到达第一个
await
语句时返回。因此,在调用函数之后,承诺将始终处于挂起状态。如果希望从该承诺中获得值,则必须使用
wait
(在另一个
async
函数中)或在承诺中使用
.then()
。除了
async
函数之外,它实际上与常规异步编程没有什么不同

Async/await不要神奇地将异步编程变成同步编程。它们在
async
函数中简化了编程,但在
async
函数之外,它只是常规的异步编程。使用
等待
然后()

另外,不要忘记使用
.catch()
正确处理错误:


正如错误所说的那样-如果您正在使用Promise的函数本身是一个
异步
函数,则只能
等待它<代码>(async()=>{const promise=getProdData(12);const data=wait promise;})()
TypeError:(中间值)(…)不是函数
 const getProdData = async function(prodNum) {
    const response = await http(`https://www.xxxxxx.com/api/products/${prodNum}/`)
    const json = await response.json()
    console.log(json)
    return json
}

getProdData(someNum).then(json => {
    // use the json in here
    console.log(json);
}).catch(err => {
    // handle errors here
    console.log(err);
});