简体   繁体   English

异步等待异常行为

[英]Async Await unusual behaviour

I am trying to understand JavaScript Async/Await feature. 我试图了解JavaScript异步/等待功能。

So I wrote a short code to understand it but it is giving me unusual behaviour/result. 所以我写了一个简短的代码来理解它,但这给了我异常的行为/结果。

 var a = 10; function load_data(data) { setTimeout(() => { a = data }, 2000); } function print() { console.log(a); } async function init() { await load_data(40); print(); } init(); 

I expect the value logged to be 40, but its logging 10 with async and await. 我希望记录的值是40,但是用async和await记录的值是10。

Async await depends on Promises , but you aren't making a promise anywhere in your code. 异步等待取决于Promises ,但是您并未在代码中的任何地方做出承诺。 As a result, awaiting load_data doesn't wait. 结果,等待load_data不会等待。

Try using a promise and resolving once the timeout fires: 尝试使用Promise并在超时触发后解决:

function load_data(data){
    return new Promise(resolve => setTimeout(() => {
        a=data
        resolve()
    }, 2000))
}

Also, we'll assume this is just for learning async/await…otherwise you should consider all the usual advice agains using global variables this way. 另外,我们假设这只是为了学习异步/等待...否则,您应该以这种方式使用全局变量考虑所有常见建议。 It's a recipe for a mess once your code gets any larger 一旦您的代码变大,这就是一团糟

 var a = 10 function load_data(data){ return new Promise(resolve => setTimeout(() => { a=data resolve() }, 2000)) } function print(){ console.log(a) } async function init(){ await load_data(40); print(); } init(); 

Async/Await is syntax used for handling promises, not just any asynchronous behavior. 异步/等待是用于处理承诺的语法,而不仅仅是任何异步行为。 For it to work with load_data , the function would need to return a promise object that resolves 40. 为了使其与load_data一起load_data ,该函数将需要返回解析为40的promise对象。

This should work how you expect: 这应该可以满足您的期望:

var a = 10

function load_data(data){
  return new Promise((resolve) => {
    setTimeout(() => {
        a=data;
        resolve(a);
    }, 2000)
  });
}

function print(){
    console.log(a)
}

async function init(){

    await load_data(40);

    print();
}

init();

Before learning about async await, learning about promises is essential since it's just a syntax over promises. 在学习异步等待之前,了解诺言是必不可少的,因为这只是诺言的一种语法。

You should return a Promise in load_data() . 您应该在load_data()返回一个Promise Actually you're returning nothing, so the code is not waiting for any value to be resolved. 实际上,您什么也不返回,因此代码不等待任何值被解析。 You should do something like this: 您应该执行以下操作:

function load_data(data){
    return new Promise( resolve => {
       setTimeout(() => {
           a=data;
           resolve(true);
       }, 2000)
    }
}

Your should create the promise. 您应该创造承诺。 Furthermore, it is better not to use a global variable, but to let the promise resolve with the desired value: 此外,最好不要使用全局变量,而应让promise解析为所需的值:

 function load_data(data){ return new Promise(resolve => { setTimeout(() => { resolve(data); //<-- pass data to resolve }, 2000) }); } async function init(){ let data = await load_data(40); // <--- get the promised value console.log(data); } init(); 

please set promise for the set your value before execute print function 请在执行打印功能之前为所设置的值设置承诺

var a = 10;
function load_data(data) {
  return new Promise(resolve => {
      a=data;
      resolve('resolved');
  });
}

async function init() {

  var result = await load_data(40);
  print();
}

function print(){
    console.log(a)
}

init();

See: manual1 manual2 请参阅: manual1 manual2

It's work for me: 这对我有用:

var a = 10

function load_data(data){
    return new Promise(resolve=>{
        setTimeout(() => {
            a=data;
            resolve('ok');
           }, 2000)    
});

}

function print(){
    console.log(a)
}

async function init(){

await load_data(40);

print();
}

init();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM