简体   繁体   English

我对异步等待感到困惑

[英]I am confused with async-await

My code should wait for 4-4 seconds for both the promise to execute total 8 seconds, but it is finishing in 4 seconds only.我的代码应该等待 4-4 秒,让两个承诺执行总共 8 秒,但它只在 4 秒内完成。 Why?为什么? Where I am thinking wrong?我在哪里想错了?

 // a promise let promise1 = new Promise(function (resolve, reject) { setTimeout(function () { resolve('Promise resolved1')}, 4000); }); let promise2 = new Promise(function (resolve, reject) { setTimeout(function () { resolve('Promise resolved2')}, 4000); }); // async function async function asyncFunc() { // wait until the promise resolves let result1 = await promise1; let result2 = await promise2; console.log(result1); console.log(result2); } // calling the async function asyncFunc();

//expected output

**//wait for 4 seconds first**
Promise resolved1 
**//wait for more 4 seconds**
Promise resolved2

//output
//waits for 4 seconds
Promise resolved1
Promise resolved2

When using async/await, your asynchronous code with begin executing, but its resolution will jump back into the synchronous code only when you use the await keyword.使用 async/await 时,您的异步代码将开始执行,但只有在您使用 await 关键字时,其解析才会跳回同步代码。 When you have multiple asynchronous functions, they will only execute sequentially when you have synchronous code running in between them because when you invoke the function is when the asynchronous portion of the code begins executing.当您有多个异步函数时,它们只会在您在它们之间运行同步代码时按顺序执行,因为当您调用函数时,代码的异步部分开始执行。 In this case, the timer starts when you invoke the function, so you need to wait for the first timer to resolve before kicking off the second timer.在这种情况下,定时器在您调用该函数时启动,因此您需要等待第一个定时器解决,然后再启动第二个定时器。

See this code snippet and check out the examples in this link to clarify.请参阅此代码片段并查看此链接中的示例以进行澄清。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

async function sequentialStart() {
  console.log('==SEQUENTIAL START==')

  // 1. Execution gets here almost instantly
  const slow = await resolveAfter2Seconds()
  console.log(slow) // 2. this runs 2 seconds after 1.

  const fast = await resolveAfter1Second()
  console.log(fast) // 3. this runs 3 seconds after 1.
}

The other issue is that when you declare your functions, you run them immediately and assign their values to variables.另一个问题是,当您声明函数时,您会立即运行它们并将它们的值分配给变量。 With minimum modification to your code, you need to set up your functions like below and only call them once you're ready to start the timer.只需对您的代码进行最少的修改,您就需要像下面这样设置您的函数,并且只有在您准备好启动计时器时才调用它们。

// a promise
let promise1 = function () {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve('Promise resolved1');
    }, 4000);
  });
};
let promise2 = function () {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve('Promise resolved2');
    }, 4000);
  });
};

// async function
async function asyncFunc() {
  // wait until the promise resolves
  let result1 = await promise1();
  console.log(result1);
  let result2 = await promise2();
  console.log(result2);
}

// calling the async function
asyncFunc();

new Promise(executor)

executor, A function to be executed by the constructor. executor,由构造函数执行的函数。 It receives two functions as parameters: resolutionFunc and rejectionFunc.它接收两个函数作为参数:resolutionFunc 和rejectionFunc。 Any errors thrown in the executor will cause the promise to be rejected, and the return value will be neglected. executor 中抛出的任何错误都会导致 promise 被拒绝,返回值将被忽略。 The semantics of executor are detailed below. executor 的语义在下面详述。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise

// a promise
let promise1 = () => new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved1')}, 4000); 
});
let promise2 = () => new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved2')}, 4000); 
});


// async function
async function asyncFunc() {

    // wait until the promise resolves 
    let result1 = await promise1(); 
    console.log(result1);
    let result2 = await promise2(); 
    console.log(result2);

}

// calling the async function
asyncFunc();

The promise 1 & 2 is already running when you declared.当您声明时,承诺 1 和 2 已经在运行。 If you want result that you expect, you should code as above.如果你想要你期望的结果,你应该像上面那样编码。

Simple defenation of assync await when yo declare async a function.当您声明async函数时,简单地声明异步等待。 The function will decleared as asyncronasly the default value of function is syncronasly .该函数将被syncronasly清除为asyncronasly函数的默认值是asyncronasly asyncronas function run block level(line by line) when you add await on a promise(function that return value) because of await compiler firstly resolved the promise and then run to next line of code asyncronas函数运行块级别(逐行)当您在承诺(返回值的函数)上添加await时,因为await编译器首先解析承诺然后运行到下一行代码

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

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