简体   繁体   English

为什么异步数组映射返回承诺而不是值

[英]Why does async array map return promises, instead of values

See the code below 见下面的代码

var arr = await [1,2,3,4,5].map(async (index) => { 
    return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(index);
            console.log(index);
        }, 1000);
    });
});
console.log(arr); // <-- [Promise, Promise, Promise ....]
// i would expect it to return [1,2,3,4,5]

Quick edit: The accepted answer is correct, by saying that map doesnt do anything special to async functions. 快速编辑:通过说map对异步功能没有做任何特殊的事情,可接受的答案是正确的。 I dont know why i assumed it recognizes async fn and knows to await the response. 我不知道为什么我认为它可以识别异步fn并知道等待响应。

I was expecting something like this, perhaps. 也许我期待这样的事情。

Array.prototype.mapAsync = async function(callback) {
    arr = [];
    for (var i = 0; i < this.length; i++)
        arr.push(await callback(this[i], i, this));
    return arr;
};

var arr = await [1,2,3,4,5].mapAsync(async (index) => { 
    return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(index);
            console.log(index);
        }, 1000);
    });
});
// outputs 1, 2 ,3 ... with 1 second intervals, 
// arr is [1,2,3,4,5] after 5 seconds.

Because an async function always returns a promise; 因为async函数总是返回promise; and map has no concept of asynchronicity, and no special handling for promises. map没有异步性的概念,也没有对诺言的特殊处理。

But you can readily wait for the result with Promise.all : 但是您可以随时通过Promise.all等待结果:

try {
    const results = await Promise.all(arr);
    // Use `results`, which will be an array
} catch (e) {
    // Handle error
}

Live Example: 现场示例:

 var arr = [1,2,3,4,5].map(async (index) => { return await new Promise((resolve, reject) => { setTimeout(() => { resolve(index); console.log(index); }, 1000); }); }); (async() => { try { console.log(await Promise.all(arr)); // Use `results`, which will be an array } catch (e) { // Handle error } })(); 
 .as-console-wrapper { max-height: 100% !important; } 

or using Promise syntax 或使用Promise语法

Promise.all(arr)
    .then(results => {
        // Use `results`, which will be an array
    })
    .catch(err => {
        // Handle error
    });

Live Example: 现场示例:

 var arr = [1,2,3,4,5].map(async (index) => { return await new Promise((resolve, reject) => { setTimeout(() => { resolve(index); console.log(index); }, 1000); }); }); Promise.all(arr) .then(results => { console.log(results); }) .catch(err => { // Handle error }); 
 .as-console-wrapper { max-height: 100% !important; } 


Side note: Since async functions always return promises, and the only thing you're await ing in your function is a promise you create, it doesn't make sense to use an async function here anyway. 旁注:由于async函数总是返回promise,而函数中await的唯一事情就是您创建的promise,因此无论如何在这里使用async函数都没有意义。 Just return the promise you're creating: 只需返回您正在创建的承诺即可:

var arr = [1,2,3,4,5].map((index) => { 
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(index);
            console.log(index);
        }, 1000);
    });
});

Of course, if you're really doing something more interesting in there, with await s on various things (rather than just on new Promise(...) ), that's different. 当然,如果您确实在其中做一些更有趣的事情,并且在各种事情上都进行了await (而不仅仅是在new Promise(...) ),那就不一样了。 :-) :-)

Since it is async, the values have not been determined at the time map returns. 由于它是异步的,因此尚未在返回map确定值。 They won't exist until the arrow function has been run. 在运行箭头功能之前,它们将不存在。

This is why Promises exist. 这就是承诺存在的原因。 They are a promise of a value being available in the future. 它们是未来价值的保证。

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

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