Javascript 异步函数返回暂挂的承诺
我不明白为什么我得到Javascript 异步函数返回暂挂的承诺,javascript,node.js,async-await,es6-promise,Javascript,Node.js,Async Await,Es6 Promise,我不明白为什么我得到Promise{},因为我使用了async/await 这是我的密码 const fetch = require("node-fetch") function getRandomPokemon() { var pokemonID = Math.floor(Math.random() * 851); console.log("The Pokemon Id is " + pokemonID); return po
Promise{}
,因为我使用了async/await
这是我的密码
const fetch = require("node-fetch")
function getRandomPokemon() {
var pokemonID = Math.floor(Math.random() * 851);
console.log("The Pokemon Id is " + pokemonID);
return pokemonID
}
async function getJSON() {
let response = await fetch('https://pokeapi.co/api/v2/pokemon/'+ pokemonID);
var json = await response.json
}
var pokemonID = getRandomPokemon()
var json = getJSON()
console.log(json)
所有
async
函数都返回一个承诺-始终。在async
函数内部使用await
会暂停该函数的执行,直到等待的承诺得到解决或拒绝,但async
函数不会阻止外部世界。wait
不会怀疑整个js解释器的执行
在async
函数中的第一个wait
点处,函数将向调用者返回一个承诺,调用者将继续执行。当函数最终在将来某个时候完成其工作时,该承诺将被解决或拒绝
我不明白为什么我会得到承诺{},因为我使用了async/await
因为所有的async
函数都返回一个承诺
您的代码中有许多问题:
getJSON()
函数没有返回值。这意味着它返回的承诺解析为未定义的
,因此无法返回其值await response.json
需要是await response.json()
pokemonID
应该作为参数传递,而不仅仅是填充到范围更大的变量中getJSON()
时,必须对其使用.then()
或wait
,以从返回的承诺中获取解析值getJSON()
函数没有返回值。这意味着它返回的承诺也会解析为未定义。而且,await response.json
需要是await response.json()
您的代码需要更像这样:
async function getJSON(id) {
const response = await fetch('https://pokeapi.co/api/v2/pokemon/'+ id);
const json = await response.json();
return json;
}
const pokemonID = getRandomPokemon();
getJSON(pokemonID).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
三个问题:
getJSON()
不返回任何内容。它需要以返回json结束代码>
async
将使其返回承诺。如果希望直接获取返回值而不是承诺,则必须使用await getJSON()
调用它。只有从另一个异步函数调用它时,才能这样做response.json
:var json=response.json()代码>
response.json
应该是一个函数
在getJSON
函数定义中,您正在执行wait response.json
。
将其更改为等待响应.json()
注意json()后面的括号
由于getJSON
函数返回promise,因此必须等待响应
在最后一行中,添加var json=await getJSON()代码>
此外,为了使用wait
,您必须将代码包装在异步函数中
将最后一行和最后第二行包装到异步函数中
异步函数resolveJSON(){
var json=await getJSON();//等待承诺兑现
log(json);
}
只是一些更改
仍然会给你承诺是的,你必须等待函数的解。在最后的第二行,
wait
getJSON函数var json=wait getJSON()
@BRUH我已经编辑了我的答案。检查一下,它现在工作得很好:)@BRUH-请务必查看我最近编辑的内容,以了解我更改的内容和原因。
const fetch = require('node-fetch');
function getRandomPokemon() {
var pokemonID = Math.floor(Math.random() * 851);
console.log('The Pokemon Id is ' + pokemonID);
return pokemonID;
}
async function getJSON() {
let response = await fetch('https://pokeapi.co/api/v2/pokemon/' + pokemonID);
var json = await response.json();
return json
}
var pokemonID = getRandomPokemon();
getJSON().then((json) => {
console.log(json);
});