Javascript异步并等待

时间:2019-02-05 07:25:02

标签: javascript asynchronous async-await

我不明白异步和等待的方式。

async function getUsername() {
    await setTimeout(function() {
        console.log("username")
    }, 100)
}

getUsername();
console.log("password")

我得到如下输出。

password
username

但是我需要使用async和await同步运行此程序。

请帮助任何人。预先感谢。

3 个答案:

答案 0 :(得分:0)

您可以将await视为“解散” Promise。目前,您的代码未使用Promise,因此await无法正常工作。相反,您可以将setTimeout包裹在一个Promise中,一旦完成,则resolve即可。然后,通过使用await,您可以从Promise获取已解析的值(仅在解析后(100m / s之后)),然后将其记录到控制台。

async函数也将始终返回Promise。因此,一旦.then函数完成,就可以在函数调用上使用getUsername方法来触发“回调”:

async function getUsername() {
    var username = await new Promise(resolve => setTimeout(function() {
        resolve("username");
    }, 100));
    
    console.log(username);
}

getUsername().then(res => {
  console.log("password")
}).catch(er => {
  console.error(er);
});

虽然上面的代码有效,但我更喜欢将我的内容记录在产生的.then回调中:

const getUsername = async _ => await new Promise(resolve => setTimeout(_ => resolve("username"), 100));

getUsername().then(result => {
  console.log(result);
  console.log("password");
}).catch(er => {
  console.error(er);
});

或者,如果您不想使用.then回调并使用async函数,则可以使用:

const getUsername = async _ => await new Promise(resolve => setTimeout(_ => resolve("username"), 100));

const getUsernameAndPassword = async _ => {
  const username = await getUsername();
  console.log(username);
  console.log("password");
}

getUsernameAndPassword();

答案 1 :(得分:0)

首先,您不能只等待setTimeout,因为它不会返回promise,如果要等待其执行,可以尝试将该函数的内容转换为一个

function getUsername() {
    return new Promise(resolve =>{
        setTimeout(function() {
            console.log("username");
            resolve();
        }, 100)
    })
}

最重要的是,如果您必须使用.then方法,那么从函数返回的promise将不会被忽略,程序将始终等待执行

getUsername().then(()=>console.log("password"));

答案 2 :(得分:0)

异步函数声明定义了一个异步函数,该函数返回一个AsyncFunction对象。

异步函数是通过事件循环异步运行的函数,

使用隐式Promise返回其结果。但是您的语法和结构

使用异步功能的代码更像使用标准同步功能。

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();

async function name([param[, param[, ... param]]]) {
   statements
}

参考文献1 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

参考2 :  https://medium.com/siliconwat/how-javascript-async-await-works-3cab4b7d21da