繁体   English   中英

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

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

见下面的代码

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]

快速编辑:通过说map对异步功能没有做任何特殊的事情,可接受的答案是正确的。 我不知道为什么我认为它可以识别异步fn并知道等待响应。

也许我期待这样的事情。

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.

因为async函数总是返回promise; map没有异步性的概念,也没有对诺言的特殊处理。

但是您可以随时通过Promise.all等待结果:

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

现场示例:

 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; } 

或使用Promise语法

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

现场示例:

 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; } 


旁注:由于async函数总是返回promise,而函数中await的唯一事情就是您创建的promise,因此无论如何在这里使用async函数都没有意义。 只需返回您正在创建的承诺即可:

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

当然,如果您确实在其中做一些更有趣的事情,并且在各种事情上都进行了await (而不仅仅是在new Promise(...) ),那就不一样了。 :-)

由于它是异步的,因此尚未在返回map确定值。 在运行箭头功能之前,它们将不存在。

这就是承诺存在的原因。 它们是未来价值的保证。

暂无
暂无

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

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