在第二个呼叫中,
var getTitleForId = async function(id) {
if (!id)
return false
let url = id + "other stuff to make a valid api call"
let response = '(null)'
await fetch(url)
.then((resp) => resp.json())
.then((responseData) => {
console.log(responseData.title);
response = responseData.title;
})
return response
}
(后来在方法中返回)将console.log(responseData.title)
分配给
response = responseData.title
,我认为这是Promise的
[object Promise]
我甚至都不会假装JavaScript是我的强项,所以如果我错过了一些小事,对不起。
Edit:通过“第二个呼叫”,我的意思是第二次访问。如果您现在查看代码,我的意思是,当我返回响应时,我会认为这将被分配
response
,而是分配了
toString()
Edit2:我也意识到“(null)”将永远不会传递,无论发生什么情况。这只是我尝试完成这项工作的多次剩菜。Edit3:我添加了整个方法
您应该做什么,所以可能是您“将其称为第二次”引起问题的方式。请解释您实际在做什么。 同一时间这可能会有所帮助
try做这个
responseData.title
或这个
[object Promise]
或作为功能(为什么不呢?)
var title = await fetch(url)
.then(resp => resp.json())
.then(responseData => responseData.title);
console.log(title);
var titlePromise = fetch(url)
.then(resp => resp.json())
.then(responseData => responseData.title);
titlePromise.then(console.log)
迅速函数将始终回报承诺;当您调用该函数时,您得到的是type type
promise(string)的对象。
https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-desver.html 您正在使用await
,因此实际上不需要打扰令人困惑的语法。 您的代码可以像这样重写:
var getTitle = url => fetch(url)
.then(resp => resp.json())
.then(responseData => responseData.title);
getTitle(url).then(console.log)
您必须在第一个电话中返回您的响应。
getTitleForId
const resp = await fetch(url);
const responseData = resp.json();
console.log(responseData.title);
const response = responseData.title;
console.log(response); // prints the title
我认为您应该使用此代码 - >
then()