【问题标题】:Is there a way to use async/await instead Promise(all) [closed]有没有办法使用 async/await 代替 Promise(all) [关闭]
【发布时间】:2020-07-14 19:21:59
【问题描述】:

我有一个 URL 数组,我需要使用 promise 或 async/await 从每个 URL 中获取 JSON 数据。 最后,我需要从源数组中的每个 URL 获取的 JSON 对象数组。 所以我想知道是否有任何方法可以用 async/await 替换 Promise(all)? 还是在这种情况下我应该使用 Promises 而不是 async/await 语法? 谢谢

【问题讨论】:

  • async/await 是调用承诺的语法糖。如果您喜欢使用 async/await 或者它使您的代码更易于阅读或(选择一个原因),那么请务必使用它。无论您是否对代码没有功能影响,这是一个偏好问题。
  • 我明白,但我很好奇 async/await 中是否有任何相当于 Promise(all) 的东西
  • Promise.all() 返回一个新的 Promise 实例,并且可以使用 async/await 结构等待任何 Promise。 await Promise.all(promise1, promise2);
  • 这几乎就是我想知道的!谢谢

标签: javascript promise async-await


【解决方案1】:

我刚刚在另一个问题中添加了这个答案: https://stackoverflow.com/a/60998022/957026

有关 aync 等待的更多信息: https://javascript.info/async-await

其他可能有用的链接: https://anasshekhamis.com/2017/11/13/callbacks-vs-promises-vs-async-awaits/

就我个人而言,我只是使用 aync/await。示例:

// if you want to use await keyword, the function should have async keyword before it
exports.callOnStartUp = async function() {
    let response;
        //  Make the call and add response to cache
        await callMarketApi().then(data => { // reading the .then here
            response = data;
        // Run your for each inside here
        }).catch(error => {
            logger.log.error('ERROR IN callOnStartUp', {
                fileName: currentFilename
            });
        });
    }
    return response;
}

function callMarketApi() {
    // Do something here, I am using an axios call for the example
    let url = 'http://some-url-you-want-to-call';
    const options = {
        method: 'GET',
        url
    }
    return Axios(options).then(response => {// returning the .then
        return response.data;
    }).catch(error => {
        // Commenting the below code as the caller can handle the error
        // logger.log.error('ERROR IN callMarketApi for ' + url, {
        //     fileName: currentFilename
        // });
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2019-09-16
    • 1970-01-01
    • 2022-01-11
    • 2023-04-08
    • 2018-05-18
    • 2017-06-13
    相关资源
    最近更新 更多