2017-01-22 1 views
2

ES6 약속을 사용하면 다음 시나리오에서 어떻게 해결할 수 있습니까?NodeJS가 약속을 깨기

addClient: function(request, response, next) { 
    var id = mongo.validateString(request.body.id); 

    mongo.Test.findOne({ 
     id: id 
    }) 
    .then(client => { 
     if (client) { 
      // want to break here 
      response.status(400).send({ 
       error: 'client already exists' 
      }); 
     } else { 
      return auth.hashPassword(mongo.validateString(request.body.secret)); 
     } 
    }) 
    .then(hashedSecret => { 
     // gets executed even if I don't return anything 
     return new mongo.Test({ 
      name: mongo.validateString(request.body.name), 
      id: id, 
      secret: hashedSecret 
     }).save(); 
    }) 
    .then(doc => { 
     return response.status(201).send({ 
      client: { 
       id: doc._id 
      } 
     }); 
    }) 
    .catch(err => { 
     return next(err); 
    }); 
} 

이 문제를 해결하는 방법을 알 수있는 명확한 문서를 찾지 못했습니다. then 체인을 연결하는 대신 처음에는 then 안에 넣을 수 있지만 더 복잡한 요청을하면 체인 연결이 가능할 수 있습니다.

+0

깨끗하고 표준적인 방법으로 이것이 가능하지는 않습니다. 유사한 내용은 [이 답변] (https://stackoverflow.com/questions/29478751/how-to-cancel-an-emcascript6-vanilla-javascript-promise-chain)을 참조하십시오. 나는 과거에 각각의'then'을 통해'null '을 반환하거나 무시 무시하게 엉망이되었습니다. 또는 "catch"문에서 중단하고 테스트하려고 할 때 던지는 것입니다.이 문장은 다시 해커라고 느껴집니다. –

답변

0
// gets executed even if I don't return anything 
return new mongo.Test({ 
     name: mongo.validateString(request.body.name), 
     id: id, 
     secret: hashedSecret 
    }).save(); 

기본 반환 값이 undefined이므로 아무 것도 반환하지 않더라도 실행됩니다. 이 값이 정의되지 않은 포함 약속 아닌 경우 그것은 undefined

으로 해결하는 코드를 가정, 그것은 this

당신은 수에 관련된 약속의 성취 값

모질라 문서가된다 그것을 일찌기 거절해서 Promise 사슬을 끊으십시오.

addClient: function (request, response, next) { 
    var id = mongo.validateString(request.body.id); 
    mongo.Test.findOne({ 
    id: id 
    }).then(client => { 
    if (client) { 
     // reject with a type 
     return Promise.reject({ 
     type: 'CLIENT_EXISTS' 
     }); 
    } 
    return auth.hashPassword(mongo.validateString(request.body.secret)); 
    }).then(hashedSecret => { 
    // gets executed even if I don't return anything 
    return new mongo.Test({ 
     name: mongo.validateString(request.body.name), 
     id: id, 
     secret: hashedSecret 
    }).save(); 
    }).then(doc => { 
    return response.status(201).send({ 
     client: { 
     id: doc._id 
     } 
    }); 
    }).catch((err) => { 
    // check type 
    if (err.type === 'CLIENT_EXISTS') { 
     return response.status(400).send({ 
     error: 'client already exists' 
     }); 
    } 
    return next(err); 
    }); 
} 
0

당신이 일명 당신이 해결하지 않습니다 약속을 반환하여 체인으로 해결되지 않은 약속을 주입 할 수있는 다음과 같은 체인 약속 링크를 실행하지 약속 체인을 중단하십시오.

new Promise((resolve, reject) => { 
    console.log('first chain link executed') 
    resolve('daniel'); 
}).then(name => { 
    console.log('second chain link executed') 
    if (name === 'daniel') { 
     return new Promise(() => { 
      console.log('unresolved promise executed') 
     }); 
    } 
}).then(() => console.log('last chain link executed')) 




// VM492:2 first chain link executed 
// VM492:5 second chain link executed 
// VM492:8 unresolved promise executed