Return 来自 Promise 的数据,并在 API 调用后将其存储在变量中
Return data from Promise and store it in variable after API Call
我是 Promises 的新手,在这里找到了很多如何访问实际值的示例,而这些值总是通过 console.log
完成的。但我的目标是将结果存储在一个变量中并使用它。
getdata = () =>
fetch(
"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo"
)
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("This is an error");
}
})
.then(data => {
console.log(data);
});
getdata();
此代码有效。你能帮我重写一下 getdata()
函数允许我将结果存储在一个变量中吗? Return 不起作用,因为我将收到另一个待处理的 Promise。
你可以这样做:
getdata = () =>
fetch(
"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo"
).then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("This is an error");
}
});
getdata().then(data => {
//I can do whatever with data
});
当然你也想处理请求失败的场景,所以你也可以链接一个.catch()
。或者,如果您为其配置了构建过程,则可以使用 async
和 await
这样您就可以:
try {
const data = await getdata();
} catch(err) {
}
这需要在标记为 async
的函数中
首先我们需要声明一个变量,比如说 temp。然后使用 fetch API 来请求我们使用 URL 的查询。如果服务器状态是 200 那么它会 return 一个承诺,我们需要使用 then
方法通过传递任何参数(res,response,r 任何...)然后是一个胖箭头函数(=>
) 这样我们就可以将响应设为 json 格式。之后我们需要使用另一个 then
方法来 return json 输出并将值分配给我们声明的临时变量。
但是,如果出现任何错误,例如 500、400、404 服务器错误,我们需要使用带有 err 参数的 catch
方法并通过控制台解决它。
let temp;
fetch('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo')
.then(res => res.json())
.then(data => temp = data)
.catch(err => console.log(err));
我是 Promises 的新手,在这里找到了很多如何访问实际值的示例,而这些值总是通过 console.log
完成的。但我的目标是将结果存储在一个变量中并使用它。
getdata = () =>
fetch(
"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo"
)
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("This is an error");
}
})
.then(data => {
console.log(data);
});
getdata();
此代码有效。你能帮我重写一下 getdata()
函数允许我将结果存储在一个变量中吗? Return 不起作用,因为我将收到另一个待处理的 Promise。
你可以这样做:
getdata = () =>
fetch(
"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo"
).then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("This is an error");
}
});
getdata().then(data => {
//I can do whatever with data
});
当然你也想处理请求失败的场景,所以你也可以链接一个.catch()
。或者,如果您为其配置了构建过程,则可以使用 async
和 await
这样您就可以:
try {
const data = await getdata();
} catch(err) {
}
这需要在标记为 async
首先我们需要声明一个变量,比如说 temp。然后使用 fetch API 来请求我们使用 URL 的查询。如果服务器状态是 200 那么它会 return 一个承诺,我们需要使用 then
方法通过传递任何参数(res,response,r 任何...)然后是一个胖箭头函数(=>
) 这样我们就可以将响应设为 json 格式。之后我们需要使用另一个 then
方法来 return json 输出并将值分配给我们声明的临时变量。
但是,如果出现任何错误,例如 500、400、404 服务器错误,我们需要使用带有 err 参数的 catch
方法并通过控制台解决它。
let temp;
fetch('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo')
.then(res => res.json())
.then(data => temp = data)
.catch(err => console.log(err));