内部有两个承诺

时间:2018-11-05 18:45:21

标签: javascript node.js asynchronous promise

我有两个承诺,就像这样:

router.get('/:address', function (req, res, next) {

    let prodotti = [];

    istanza.methods.getProductByOwner("xxxxx").call().then(
        ids => {
            for (let id of ids) {
                istanza.methods.prodotti(id).call().then(
                    prod => {
                        prodotti.push(prod);
                    },
                    error => console.dir(error)
                )
            }
        },
        err => console.log("ritiro KO " + err)
    );

    res.render('profilo', {address: req.params.address, prodotti: prodotti});

});

当for结束时,我想充斥prodotti。

我这样尝试:

router.get('/:address', function (req, res, next) {
    let prodotti = [];

    istanza.methods.getProductByOwner("xxxx").call().then(
        ids => {
            f(ids)
        },
        err => console.log("ritiro KO " + err)
    );
    res.render('profilo', {address: req.params.address, prodotti: prodotti});

});

然后

async function f(ids) {
    let prodotti = [];
    let promises = []

    promises.push(new Promise((resolve, reject) => {
        for (let id of ids) {
            promises.push(istanza.methods.prodotti(id).call().then(
                prod => {
                    prodotti.push(prod);
                    //resolve when for is finished
                    if(id == (ids.length)-1){
                        resolve(prodotti)
                    }
                    id++;
                },
                error => console.dir(error)
            ));
        }

    }));

    let result = await Promise.all(promises);
    console.log("await " + result);
}

但是我的结果是:

  

、、、 [对象对象],[对象对象],[对象对象]

我只想在for结束时获得结果,并且我不喜欢使用这样的条件:

if(id == (ids.length)-1)

2 个答案:

答案 0 :(得分:1)

似乎您需要正确处理来自初始api渲染器的承诺:

router.get('/:address', async (req, res, next) => {   
    let ids = await istanza.methods.getProductByOwner("xxxx").call().catch(err => 
        console.log("ritiro KO " + err)
    );
    let prodotti = await Promise.all(ids.map( async f ));
    res.render('profilo', {address: req.params.address, prodotti: prodotti});

});

您的其他函数然后可以分别处理每个id:

function f(id) {
    return istanza.methods.prodotti(id).call().catch(console.dir)
}

我假设有几件事,例如.call()方法返回一个promise(从语法上看,确实如此)。警告,此代码未经测试!

注意:使用Bergi的评论进行了更新

答案 1 :(得分:0)

您必须遍历每个ids值,并将promise推送到数组中,然后等待所有promise被解决。解决后,您可以在result中获得响应并将其推送到prodotti

尝试一下

let promises = [];
async function f(ids) {

    for (let id of ids) {
       var promise = istanza.methods.prodotti(id).call().then(
                prod => {
                   return prod;
                },
                error => return error;
            );
        promises.push(promise);    
  }
    let prodotti = await Promise.all(promises);
    console.log("await " + prodotti);
}