这是函数:
export const getSafestCountriesNames = async() => {
try{
const names = await getCountriesData();
names.forEach((country) => {
const {score} = country.advisory;
if(score == 0){
const liEl = createDOMElement('li', {className: 'name'});
liEl.innerHTML = `${country.name}`;
return liEl;
}
});
}
// …
}
当我在这里调用它时,我得到 undefined
:
async function func(){
const names = await getSafestCountriesNames();
console.log(names);
}
func();
答案 0 :(得分:1)
它返回 Promise{pending}
因为当一个函数有 async
关键字时,它必须返回一个 Promise。见here。
尽管如此,您的代码中存在更深层次的问题。您的 return 语句位于 forEach
的回调中。那是回调的 return 语句,而不是 getSafestCountriesNames
的那个。
由于您需要返回一个 Promise(因为您使用的是 await
),您可以将您的逻辑包装在如下内容中:
return new Promise((resolve, reject) => {
// your logic here, resolving or rejecting instead of just returning
})
或保持简单:return Promise.resolve("something")
当您使用 await
调用该函数时,它会解析 undefined
,因为您没有解析 Promise 中的任何内容。