node.js - promise嵌套的问题,后面一个then用到前面的then的返回值。
阿神
阿神 2017-04-17 14:40:26
0
3
586

nodejs中关于ES6的promise嵌套写法
我打算实现如下功能:插入主记录,返回insertId,然后插入明细记录

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

这种逻辑似乎又进入了无限嵌套逻辑。求教如何写正确!

阿神
阿神

闭关修行中......

reply all(3)
左手右手慢动作
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(..)
洪涛
testObject.insertMain(code,name)
.then((result1)=>{
    return testObject.insertDetailf(result1.id,......)
}).then(function(result){
    console.log('finish');
}).catch(function(err){
    console.log(err.stack);
})
伊谢尔伦

Transforming non-Promise implementation into Promise implementation is a huge project. It would be easier if they were all implemented by Promise. The first Promise's then returns the value of the second Promise or the second then, and you can keep then going on, and finally catch it.

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' }
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template