我正在尝试从下面的脚本中获取价值,但它不能
let doGetVexLastInfo = (url) => {
fetch(url)
.then(res => res.json())
.then(json => {
let result = 1000 / json.ticker.last;
return result.toFixed(4);
});
}
console.log(doGetVexLastInfo(url))发布于 2020-06-12 18:53:11
Fetch是一个异步调用。在这里,您正在尝试将异步调用和同步调用混合在一起。你所要达到的目标的正确用法和定义如下
let doGetVexLastInfo = (url) => {
return fetch(url)
.then(res => res.json())
.then(json => {
let result = 1000 / json.ticker.last;
return Promise.resolve(result.toFixed(4));
});
}
doGetVexLastInfo(url)
.then(result => console.log(result))现在,doGetVexLastInfo函数返回一个promise,解析该promise时会给出正确的结果。
发布于 2020-06-12 18:36:21
您应该返回fetch(),以便可以使用.then()访问"result.toFixed(4)"
let doGetVexLastInfo = (url) => {
return fetch(url)
.then(res => res.json())
.then(json => {
let result = 1000 / json.ticker.last;
return result.toFixed(4);
});
}
// with .then()
doGetVexLastInfo(url)
.then(console.log)
.catch(console.error)
// with await
(async (){
const output = await doGetVexLastInfo(url);
console.log(output)
})();https://stackoverflow.com/questions/62342401
复制相似问题