Mic*_*ant -1 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))
Run Code Online (Sandbox Code Playgroud)
给我:
4. userId = 1
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用等待时
{
async function doFetch() {
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log('8. await: ' + String(result.json()));
} doFetch();
}
Run Code Online (Sandbox Code Playgroud)
我得到的承诺是作为输出
8. await: [object Promise]
Run Code Online (Sandbox Code Playgroud)
如何获取 JSON 值?
谢谢各位的解答:
console.log('8. await: ' + String(await result.json()));
Run Code Online (Sandbox Code Playgroud)
我应该更清楚,如何获取 userId?我试过
console.log('8. await: ' + String(await result.json().userId));
Run Code Online (Sandbox Code Playgroud)
但我没有定义
当您在第一个版本中需要两次then
调用时,预计await
在第二个版本中也需要两次调用。该json()
方法返回一个承诺。
所以改变:
console.log('8. await: ' + String(result.json()));
Run Code Online (Sandbox Code Playgroud)
到:
console.log('8. await: ' + String(await result.json()));
Run Code Online (Sandbox Code Playgroud)
要获得一个属性,只需像往常一样操作,但要确保您已经等待了该对象。所以首先关闭括号:
console.log('8. await: ' + String(result.json()));
Run Code Online (Sandbox Code Playgroud)
如果您需要的不仅仅是一个属性,那么首先将整个对象放入一个变量中,然后使用该变量:
console.log('8. await: ' + String(await result.json()));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3412 次 |
最近记录: |