繁体   English   中英

Javascript Promise with Await解释

[英]Javascript Promise with Await Explanation

我只想了解承诺和等待如何一起工作。 看下面的代码:

console.log("One: Started");
setTimeout(function(){console.log("One: Completed")}, 1000);
console.log("Two: Started");
setTimeout(function(){console.log("Two: Completed")}, 2000);
console.log("Three: Started");
setTimeout(function(){console.log("Three: Completed")}, 3000);

所以这当然记录:

One: Started
Two: Started
Three: Started
One: Completed
Two: Completed
Three: Completed

我希望在下一个开始之前完成一个。 我用承诺和等待的理解写了这个,但这不起作用。 有人请尝试编辑此代码以使其正常工作。 请和解释,因为我想了解承诺和等待

async function LogAll() {
    console.log("One: Started");
    await function() {
        return new Promise((resolve, reject) => {
            setTimeout(function(){
                console.log("One: Completed");
                resolve();
            }, 1000);
        });
    }
    console.log("Two: Started");
    await function() {
        return new Promise((resolve, reject) => {
            setTimeout(function(){
                console.log("Two: Completed");
                resolve();
            }, 2000);
        });
    }
    console.log("Three: Started");
    await function() {
        return new Promise((resolve, reject) => {
            setTimeout(function(){
                console.log("Three: Completed");
                resolve();
            }, 3000);
        });
    }
}

LogAll();

你需要await 承诺 ,而不仅仅是功能。 当您await function ... (不调用它)时,该函数将被计算为表达式,然后被丢弃。 只需调用函数:

 async function LogAll() { console.log("One: Started"); await (function() { return new Promise((resolve, reject) => { setTimeout(function() { console.log("One: Completed"); resolve(); }, 1000); }); })(); console.log("Two: Started"); await (function() { return new Promise((resolve, reject) => { setTimeout(function() { console.log("Two: Completed"); resolve(); }, 2000); }); })(); console.log("Three: Started"); await (function() { return new Promise((resolve, reject) => { setTimeout(function() { console.log("Three: Completed"); resolve(); }, 3000); }); })(); } LogAll(); 

或者,对于这个例子,根本不使用函数 - 直接等待promises:

 async function LogAll() { console.log("One: Started"); await new Promise((resolve, reject) => { setTimeout(function() { console.log("One: Completed"); resolve(); }, 1000); }); console.log("Two: Started"); await new Promise((resolve, reject) => { setTimeout(function() { console.log("Two: Completed"); resolve(); }, 2000); }); console.log("Three: Started"); await new Promise((resolve, reject) => { setTimeout(function() { console.log("Three: Completed"); resolve(); }, 3000); }); } LogAll(); 

async function声明定义了一个asynchronous function ,它返回一个AsyncFunction对象。

async function可以包含一个await表达式,该表达式暂停执行async function并等待传递的Promise's解析,然后恢复async function's执行并返回已解析的值。

 function resolveAfter2Seconds() { return new Promise(resolve => { setTimeout(() => { resolve('calling'); }, 2000); }); } async function asyncCall() { var result = await resolveAfter2Seconds(); console.log(result); // expected output: "resolved" console.log('called'); } asyncCall(); 

有关更多信息,请参阅Async Await

什么是异步功能:

它是一个返回AsyncFunction对象的函数,类似于Promises。 如果它抛出错误,则对象拒绝,否则当它返回值时,它会解析。

异步函数是更新的,在它们存在之前,有不同的方法来编写异步代码:Promises(rxjs的一部分),Observables(“无限Promises”),与定时事件一起使用的回调。

什么是await关键字:

在Javascript中, await关键字只能在async函数中使用,语法如下:

[returnValue] = await expression;

表达式可以是Promise或异步代码返回的任何其他值。

await告诉代码停止并等待该值。

如果没有这个,上面表达式中的returnValue将立即被赋予一个值(最可能未定义),代码将继续而不会阻塞。 在代码中的一些未知时间和未知点之后,函数将最终返回并且returnValue将最终接收到正确的值。 但也许代码前进并错误地假设您已经有一个已定义和更新的值,可能会失败。

尝试在没有异步等待的情况下运行代码段。 它们是显示相应同步代码的反例:

例1:所有Promise立即启动

 function LogAll() { console.log("One: Started"); new Promise((resolve, reject) => { setTimeout(function() { console.log("One: Completed"); resolve(); }, 1000); }); console.log("Two: Started"); new Promise((resolve, reject) => { setTimeout(function() { console.log("Two: Completed"); resolve(); }, 2000); }); console.log("Three: Started"); new Promise((resolve, reject) => { setTimeout(function() { console.log("Three: Completed"); resolve(); }, 3000); }); } LogAll(); 

例2:完全没有承诺(与例1相同的结果)

 function LogAll() { console.log("One: Started"); setTimeout(function() { console.log("One: Completed"); }, 1000); console.log("Two: Started"); setTimeout(function() { console.log("Two: Completed"); }, 2000); console.log("Three: Started"); setTimeout(function() { console.log("Three: Completed"); }, 3000); } LogAll(); 

在示例2中请注意,setTimeout是一个计时事件,是Javascript的旧功能,因此它并不需要包装器Promise,除了Promise允许您抛出错误并拒绝。

暂无
暂无

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

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