为什么异步数组映射返回承诺而不是值 [英] Why does async array map return promises, instead of values

查看:71
本文介绍了为什么异步数组映射返回承诺而不是值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见下面的代码

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并知道等待响应.

Quick edit: The accepted answer is correct, by saying that map doesnt do anything special to async functions. I dont know why i assumed it recognizes async fn and knows to await the response.

也许我期待这样的事情.

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.

推荐答案

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

Because an async function always returns a promise; and map has no concept of asynchronicity, and no special handling for promises.

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

But you can readily wait for the result with 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语法

or using Promise syntax

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函数.只需返回您正在创建的承诺即可:

Side note: Since async functions always return promises, and the only thing you're awaiting in your function is a promise you create, it doesn't make sense to use an async function here anyway. 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);
    });
});

当然,如果您真的在其中做一些更有趣的事情,并且在各种事物上使用await(而不是仅仅在new Promise(...)上),那就不一样了. :-)

Of course, if you're really doing something more interesting in there, with awaits on various things (rather than just on new Promise(...)), that's different. :-)

这篇关于为什么异步数组映射返回承诺而不是值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆