Nic*_*Dry 1 javascript api asynchronous
我有一个API调用,它使用回调迭代返回的JSON,然后我想将结果输出到控制台.问题是我觉得即使这应该异步进行,我也在使用then()调用,我认为它会等待返回并正确打印出来.但是在第一次调用时,它会在控制台中打印出一个空数组,然后在第二个按钮上按下它会正确记录数组.
function getPrice() {
var valueArray = [];
var symbol = document.getElementById("symbol_input").value;
var url = "https://api.iextrading.com/1.0/stock/" + symbol + "/chart"
fetch(url)
.then(res => res.json())
.then(function(res) {
res.forEach(element => {
valueArray.push(element);
});
})
.then(console.log(valueArray))
.catch(err => console.log(err));
}Run Code Online (Sandbox Code Playgroud)
<input type="input" id="symbol_input">
<button id="priceButton" onclick="getPrice()">Get Price</button>Run Code Online (Sandbox Code Playgroud)
.then接受函数作为参数,而不是简单的语句.then(console.log(valueArray)).完成之后,console.log将立即执行(在fetch完成之前).
请改用功能.(使用示例输入:"abc")
function getPrice() {
var valueArray = [];
var symbol = document.getElementById("symbol_input").value;
var url = "https://api.iextrading.com/1.0/stock/" + symbol + "/chart"
fetch(url)
.then(res => res.json())
.then(function(res) {
res.forEach(element => {
valueArray.push(element);
});
})
.then(() => console.log(valueArray))
.catch(err => console.log(err));
}Run Code Online (Sandbox Code Playgroud)
<input type="input" id="symbol_input">
<button id="priceButton" onclick="getPrice()">Get Price</button>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
492 次 |
| 最近记录: |