[英]Use a promise result from a fetch-api in an if statement of another function - JS
So I have this fetch-api所以我有这个 fetch-api
let test = () => fetch(usd_api).then(response => response.json())
.then(data => data.exchange_rates.dash_usd);
Console log控制台日志
let console_test = () => {console.log(test())}
How can use this number [[PromiseResult]]: 134.445...
in the following function where the number 150 is.如何使用此数字
[[PromiseResult]]: 134.445...
在以下 function 中,其中数字150是。
function main(){
fetch(txs_api).then(response => response.json()).then(function(data) {
var amount = data.txs[0].vout[1].value;
if(amount == 150){
// SUCCESS!
$('#modal').modal('hide');
console.log('requests stopped');
clearInterval(interval);
}
})
}
let test = () => fetch(usd_api)
.then(response => response.json())
.then(data => data.exchange_rates.dash_usd);
You want too keep using the same promise, if you want to log the result of your promise you need to wait for it to be completed:你也想继续使用相同的 promise,如果你想记录你的 promise 的结果,你需要等待它完成:
// with .then()
test().then(console.log);
// or with await if you can:
console.log(await test());
I figured it out.我想到了。 Don't know if it's the best way to do it but it's working.
不知道这是否是最好的方法,但它正在工作。
function main(){
fetch(usd_api).then(response => response.json()).then(function(data) {
var dash_price = data.exchange_rates.dash_usd;
fetch(txs_api).then(response => response.json()).then(function(data) {
var amount = data.txs[0].vout[1].value;
if(amount == dash_price){
// SUCCESS!
$('#modal').modal('hide');
console.log('requests stopped');
clearInterval(interval);
}
})
})
}
Do not return value.不返回值。 Because it returns to below function
因为返回到下面function
function(data) {
return data.exchange_rates.dash_usd
}
If you want to return your value to a variable you have to use Promise like below.如果你想将你的值返回给一个变量,你必须像下面这样使用Promise 。
let test = new Promise((resolve, reject) => {
fetch(usd_api).then(response => response.json())
.then(function (data) {
resolve(data.exchange_rates.dash_usd)
});
})
async function demo(){
let console_test = await test
console.log(console_test )
}
demo()
Note : Do not forget to use async and await
注意:不要忘记使用异步和等待
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.