这里完全是JS新手。我们的办公室使用HCL Leap构建表单,我需要编写一些javascript代码来填充表单。不幸的是,我遇到的所有示例都是将结果在线输出到console.log。我需要它真正被赋值给一个变量。下面是我一直在尝试使用的一些代码的示例,这些代码应该使用json输出填充表单文本区域:
var UserInfo = (async function getUserInfo() {
var response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
console.log(response.json())
})();
item.setValue(UserInfo);
当我预览代码时,表单填充了"object Promise“。我认为这是代码编写方式的某种时间问题。有人有什么建议吗?
发布于 2020-09-11 19:06:00
Fetch返回一个Promise而不是response。稍后可以将响应解析为纯文本或json (就像您所做的那样)。问题是response.json()
也会返回一个Promise。所以在response.json()
之前你需要等待。完整的代码应该是:
var UserInfo = await (async function getUserInfo() {
try{
var response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
var jsonResponse = await response.json()
return jsonResponse
}
catch(e){
console.error(e)
}
})();
item.setValue(UserInfo);
或者在一行中
var UserInfo = await (await fetch('https://jsonplaceholder.typicode.com/todos/1')).json()
if(UserInfo)
item.setValue(UserInfo)
每当使用async/await时,都应该始终将其包装在try/catch块中,因为它可能会返回错误而不是结果
发布于 2020-09-11 19:07:45
你需要await
所有的东西:
var UserInfo = (async function getUserInfo() {
var response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
// ``.json` also returns a promise, so use `await` to reference the actual result
const data = await response.json()
console.table(data)
// Since this variable comes from a function expression, explicitly return
// `response.json()` to set the final value as intended
return data
})();
item.setValue(await UserInfo);
如果主执行上下文(使用item.setValue
)不在async
函数中,那么为了使用await
来设置item.value()
,您必须用异步生命周期对其进行包装。
关键字await仅在异步函数内部有效。如果你在异步函数体之外使用它,你会得到一个SyntaxError。Source: MDN
(async () => {
var UserInfo = await (async function getUserInfo() {
var response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
// ``.json` also returns a promise, so use `await` to reference the actual result
const data = await response.json()
console.table(data)
// Since this variable comes from a function expression, explicitly return
// `response.json()` to set the final value as intended
return data
})();
item.setValue(UserInfo);
})();
如果您需要避免在上面的作用域中使用async
包装器,这里有另一种方法:
// Simplify this method, not an IIFE any more
async function getUserInfo() {
var response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
const data = await response.json()
console.table(data)
return data
};
// This part doesn't need to exist inside an async function
getUserInfo()
.then((info) => item.setValue(info))
.catch((err) => console.error(err))
发布于 2020-09-11 19:09:45
const UserInfo = async () => {
const response = await
fetch('https://jsonplaceholder.typicode.com/todos/1');
return response.json();
};
UserInfo().then(data => {
console.log(data)
//set data to field
//item.setValue(data)
}).catch(error => {
throw error
})
https://stackoverflow.com/questions/63852719
复制相似问题