【问题标题】:Access URL in promise each访问每个承诺中的 URL
【发布时间】:2018-10-24 16:53:38
【问题描述】:

我正在使用 Bluebird.js 和 request-promise NPM 模块。 我想访问 promise URL 或 item.transactionID,如下面的代码所示。 我试图找到很多东西但没有工作 我们怎样才能做到这一点。

    paymentIDArray.forEach(item => {
        let p = rp({
            uri: API + item.transactionID,
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Basic " + authCode
            },
            simple: false,
            resolveWithFullResponse: false,
            transform2xxOnly: false
        }).promise();
        promises.push(p);
    });

    await Promise
        .all(promises)
        .each(async (inspection) => {
            if (inspection.isFulfilled()) {

               // I want item.transactionID of each promise here

                let result = JSON.parse(inspection.value());

            } else {
                logger.error(inspection);
                logger.error("A promise in the array was rejected with", inspection.reason());
            }
        });

【问题讨论】:

    标签: javascript node.js promise bluebird


    【解决方案1】:

    您可以将item.id 添加到您推送的承诺值

    paymentIDArray.forEach(item => {
        let p = rp({
            uri: API + item.transactionID,
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Basic " + authCode
            },
            simple: false,
            resolveWithFullResponse: false,
            transform2xxOnly: false
        }).promise();
        promises.push(p.then(inspection => ({inspection, id: item.id})));
    });
    
    // each promise, instead of being just the result of `rp` is now {inspection: result of rp, id: item.id}
    await Promise
    .all(promises)
    //    vvvvv do you really need async? you are not awaiting in this code
    .each(async ({inspection, id}) => {
        if (inspection.isFulfilled()) {
    
            // id is the required item.id
    
            let result = JSON.parse(inspection.value());
    
        } else {
            logger.error(inspection);
            logger.error("A promise in the array was rejected with", inspection.reason());
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2019-06-16
      • 2018-02-28
      • 2013-12-08
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      相关资源
      最近更新 更多