[英]JS await not working as expected
It's my first time working with async js, and it doesn't work as expected. 这是我第一次使用异步js,它没有按预期工作。
Here is a simple form of the problematic code: 这是有问题的代码的一种简单形式:
let input = document.querySelector( '#test' ); document.querySelector( '#btn' ).addEventListener( 'click', getIP ); document.querySelector( '#btn-2' ).addEventListener( 'click', test ); async function test() { let value = input.value; if ( !value ) { await getIP(); value = input.value; } alert( value ); // do something with `value` } function getIP() { fetch( 'https://httpbin.org/get' ).then( res => { return res.json(); }).then( json => { input.value = json.origin }); }
<input id="test" type="text" /> <input type="button" id="btn" value="load" /> <input type="button" id="btn-2" value="execute something" />
This code is suppose to let the user to load their IP into the box, and then other buttons ( which are not shown in this example ) can execute actions using this IP. 假设此代码允许用户将其IP加载到框中,然后其他按钮(在此示例中未显示)可以使用此IP执行操作。
However, there is a button ( #btn-2
) which executes a single action using the IP. 但是,有一个按钮(
#btn-2
)使用IP执行单个操作。
The problem is that I wanna let the users to execute the action of #btn-2
immediately, without clicking the load
button. 问题是我想让用户立即执行
#btn-2
的操作,而无需单击load
按钮。
How can I make it work? 我该如何运作?
You actually just need a Promise from getIp
: 您实际上只需要
getIp
的Promise getIp
:
function getIP() {
return fetch( 'https://httpbin.org/get' )
.then(res => res.json());
}
Then it is as easy as: 然后就这么简单:
async function test(){
input.value = input.value || await getIP();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.