DWQA QuestionsCategory: ProgramFor the problem of promise nesting, the next then uses the return value of the previous then.
Enthusiastic Wang Zongyue asked 2 months ago

Promise nested writing of ES6 in nodejs
I plan to implement the following functions: insert the master record, return the InsertID, and then insert the detail record

testObject.insertMain(code,name)
.then((result)=>{
    var insertId = result.insertId;
    testObject.insertDetail(insertId,........)
    .then((result1)=>{
        testObject.func3(......)
        .then(..)
        .catch(..)
    })
    .catch(..)
.catch(..)

This kind of logic seems to enter into the infinite nesting logic again. Ask how to write correctly!

3 Answers
Best Answer
xialeistudio answered 2 months ago
testObject.insertMain(code,name)
.then((result)=>{
    var insertId = result.insertId;
    return insertId;
})
.then(function(insertId){
    return testObject.insertDetail(insertId);
})
.then(function(detail){
    console.log(detail);
})
.catch(..)
xialeistudio replied 2 months ago

testObject.insertMain(code,name)
.then((result)=>{
var insertId = result.insertId;
return insertId;
})
.then(function(insertId){
return testObject.insertDetail(insertId).then(function(data){
return [data,insertId];
});
})
.then(function(data){
console.log(data[0],data[1]);
})
.catch(..)

Border town answered 2 months ago

Transforming a non promise implementation into a promise implementation is a huge project. If it’s all promise implementation, it’s easy. The first promise’sthenReturn is the second promise or the secondthenYou can alwaysthenGo on, and finally catch.
xxx.then().then().then().then().catch()

function insertMain() {
    return Promise.resolve("main result");
}

function insertDetail(result) {
    return Promise.resolve({
        main: result,
        detail: "detail result"
    });
}


insertMain().then(result => {
    return insertDetail(result);
}).then(r => {
    console.log(r);
    // { main: 'main result', detail: 'detail result' }
    r.more = "more result";
    return Promise.resolve(r);
}).then(r => {
    console.log(r);
    // { main: 'main result',
    //  detail: 'detail result',
    //  more: 'more result' }
});
Li Teng Fei answered 2 months ago
testObject.insertMain(code,name)
.then((result1)=>{
    return testObject.insertDetailf(result1.id,......)
}).then(function(result){
    console.log('finish');
}).catch(function(err){
    console.log(err.stack);
})