Javascript 如何使用wait而不是just获取我的json值
这很有效Javascript 如何使用wait而不是just获取我的json值,javascript,promise,async-await,async.js,Javascript,Promise,Async Await,Async.js,这很有效 fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(json => console.log('4. userId = ' + json.userId)) 给我: 4. userId = 1 但是当我尝试使用wait时 { async function doFetch() { const result = await
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log('4. userId = ' + json.userId))
给我:
4. userId = 1
但是当我尝试使用wait时
{
async function doFetch() {
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log('8. await: ' + String(result.json()));
} doFetch();
}
我得到的是作为输出的承诺
8. await: [object Promise]
如何获取JSON值
使现代化
感谢您的回答:
console.log('8. await: ' + String(await result.json()));
但是我应该更清楚,如何获取用户ID?我试过了
console.log('8. await: ' + String(await result.json().userId));
但是我得到了未定义的当您在第一个版本中需要两个then调用,然后在第二个版本中需要两个等待。json方法返回一个承诺
因此,改变:
console.log('8. await: ' + String(result.json()));
致:
要获取属性,只需像往常一样操作,但要确保您已首先等待对象。因此,首先关闭括号:
异步函数{
const result=等待获取'https://jsonplaceholder.typicode.com/todos/1';
console.log'8.await:'+await result.json.userId;
}; json将返回您需要等待的承诺
目前,您正在将result.json返回的Promise对象转换为字符串,这就是控制台上记录的内容
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await result.json();
console.log('8. await: ' + data);
编辑:
如何获取用户ID
由于您正在将wait result.json返回的对象转换为字符串,并且当任何对象转换为字符串时,您将得到类似于[object object]的内容,所以您将无法定义该对象
只是不要将await result.json返回的对象转换为字符串并简单访问userId属性
请参阅下面的代码片段
异步函数fetchData{
const result=等待获取'https://jsonplaceholder.typicode.com/todos/1';
const data=wait result.json;
console.logStringdata;//您正在执行的操作
console.logdata;//您应该做什么
}
获取数据;谢谢-如何获得实际的用户ID?请参阅答案的补充。如果您需要访问更多属性,那么最好将等待的结果放入一个变量中,并继续使用该变量…再次感谢trincot。但是,我在console.log'8中没有定义。等待:'+Stringawait result.json.userId;我尝试了.blob totry输出JSON.stringifywait result.JSON,null,2来查看您得到的实际对象结构。也许它是一个数组……如果您参考了jsonplaceholder响应,那么可以看到我添加到答案中的代码片段。您可以运行并查看输出的用户id。修复了user=1的打字错误,将其硬编码为用户id代码实际包含的内容
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await result.json();
console.log('8. await: ' + data);
console.log('8. await: ' + (await result.json()).userId);