javascript - 异步等待函数的奇怪行为

标签 javascript function asynchronous es6-promise

我有以下异步代码示例:

// Functions

function getSomePromise() {
    let a = new Promise((resolve, reject) => {    
        setTimeout(function(){
            console.log("Inside promise...");
            resolve("Success!"); 
        }, 1000);
    });

    return a;
}

async function someWrapper(i) {
    console.log('A: '+ i);
    await getSomePromise();
    console.log('B: ' + i);    
}

还有两个测试:

async function test1() {
    for(let i=0; i<5; i++) {
        // body copy-pasted of someWrapper function:
        console.log('A: '+ i);
        await getSomePromise();
        console.log('B: ' + i);
    }    
}

async function test2() {
    for(let i=0; i<5; i++) {
        someWrapper(i);                
    }    
}

下面是分别运行 test1()test2() 后 chrome 控制台中的结果:

Test 1               |      Test 2
---------------------------------------------
A: 0                 |      A: 0
Inside promise...    |      A: 1
B: 0                 |      A: 2
A: 1                 |      A: 3
Inside promise...    |      A: 4
B: 1                 |      Inside promise...
A: 2                 |      B: 0
Inside promise...    |      Inside promise...
B: 2                 |      B: 1
A: 3                 |      Inside promise...
Inside promise...    |      B: 2
B: 3                 |      Inside promise...
A: 4                 |      B: 3
Inside promise...    |      Inside promise...
B: 4                 |      B: 4

问题:为什么当我们在for-loop (test2) 中使用函数someWrapper() 时,我们得到的结果与我们复制的结果不同-将此函数体直接粘贴到 for-loop (test1) 中?

(上面的示例非常抽象,但是“我发现了这种行为”是在调用 ajax 请求时(而不是 console.log('A: '+ i);console.log( 'B: '+ i);) 在我的应用程序中哪个序列非常重要(请求 A1 必须在请求 B0 之前...))

最佳答案

看评论

@HMR - hm... I not understand - in question example there is async function someWrapper() but that function don't return anything (it even doesn't have return statement (!) ) - can you explain what do you mean by async functions immediately return a promise? - Kamil Kielczewski

看来你不明白async await。我通常建议人们在理解 promise 之前停止等待。然而,在下一个问题的评论中,我给你答案:

someWrapper will immediately return a promise that resolves to undefined. The await only "waits" in the someWrapper function but the function calling someWrapper will immediately receive a promise that resolves in undefined. Functions always return something, if you don't in code then it will return undefined. If it's an async function without a return then it'll return a promise that resolves in undefined - HMR.

Await 是 promises 的语法糖(更好看的代码),实际上并不等待任何东西。

也许下面的代码可以解决问题:

var test = async () => {
   await 22;//doesn't even matter if value is promise
   console.log("after wait");
}
var result = test();
console.log("outside test we don't wait for anything",result);

如果您不明白为什么该代码的输出是:

outside test we don't wait for anything Promise {< pending >}

after wait

然后我建议您只使用 promises,直到您这样做为止。

关于javascript - 异步等待函数的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48670283/

相关文章:

javascript - Jquery 测验 - 不会调用最后一个 if

performance - 将 Scala Map 作为参数传递给函数需要太多时间

c# - 无法读取 ASP.NET WebApi Controller 中的 Request.Content

javascript - 如何让 npm 包 bin 使用实验模块选项运行?

javascript - A 帧 Raycaster 不工作(需要与天空的交点)

string - 使用空接口(interface)更改函数中的 arg

php - WooCommerce:如何检查特定产品是否存在元 key

javascript - 异步 Angular Promise 和变量初始化

javascript - 使用异步库组装数据库中的所有标签

javascript - 如何使用 JavaScript 从 HTML 页面的嵌入/对象中获取元素?