JavaScript中的Promise问题

时间:2019-02-26 20:20:43

标签: javascript ecmascript-6 es6-promise web3 web3js

我是新来的。我将不胜感激。最后一行代码不起作用。不知道如何解决。我知道第二个“ then”必须返回resolve(),但如何实现

let getNumber = new Promise((resolve) => {
    //API
    EthereumNote.getAmountOfMyNotes(function(error, result) {
        if (!error) {
            let AmountOfMyNotes = Number(result)
            resolve(AmountOfMyNotes)
            console.log(result)
        } else
            console.error(error)

    })
}).then(result => {
    return new Promise((resolve) => {
        for (let i = 0, p = Promise.resolve(); i < result; i++) {
            p = p.then(_ => new Promise(resolve => {
                //API
                EthereumNote.getMyNote(i, function(error, result) {
                    if (!error) {
                        let text = String(result[0])
                        let noteID = Number(result[1])
                        console.log(text)
                        console.log(noteID)
                        resolve()
                    } else
                        console.error(error)
                })
            }));
        }
    })
}).then(() => console.log('Hi!')) // this one doesn't work

1 个答案:

答案 0 :(得分:1)

避免使用Promise constructor antipattern!可以用new Promise来包装EthereumNote.getMyNote,也不能用循环来包装。您永远不会resolve()那个外部承诺。

相反,只需返回您在p中创建的承诺链即可:

let getNumber = new Promise((resolve) => {
    //API
    EthereumNote.getAmountOfMyNotes(function(error, result) {
        if (error) reject(error);
        else resolve(Number(result));
    })
}).then(amountOfMyNotes => {
    console.log(amountOfMyNotes);
    var p = Promise.resolve();
    for (let i = 0; i < amountOfMyNotes; i++) {
        p = p.then(_ => new Promise((resolve, reject) => {
            //API
            EthereumNote.getMyNote(i, function(error, result) {
                if (error) reject(error);
                else resolve(result);
            });
        })).then(result => {
            let text = String(result[0])
            let noteID = Number(result[1])
            console.log(text)
            console.log(noteID))
        });
    }
    return p;
}).then(() => {
    console.log('Hi!'); // this one now works
}, err => {
    console.error(err);
});