2017-11-28 3 views
0

나는 몽구스 약속 배열을 전달하며 때로는 customerFindPromise가 null을 반환하고 때로는 요청 된 객체를 반환합니다. 내가 여기서 뭔가 잘못하고있는 중이 야nodejs Promise.all은 일부 몽구스 약속에 대해 null을 반환합니다.

******************** START result0: null result END ******************** 
******************** START result1: { _id: 5a18a637346826574416a588, 
doc_fname: 'Bob', 
doc_lname: 'Smith', 
numOfCases: 1, 
__v: 0 } result END ******************** 
******************** START result2: {"n":1,"ok":1} result END ******************** 

코드

var customer = { 
    doctor_id: 5a18a637346826574416a588, 
    cust_fname: 'dfsdf', 
    cust_lname: 'sdasd', 
    case_type: 'Crowns', 
    _id: 5a1cd19438f14164b0087753 
} 
test(customerCase); 
async function test(customerCase) { 

    console.log("******************** customerCaseDelete: "+ customerCase._id +" ********************"); 
    var _id = customerCase._id; 
    var doctor_id = customerCase.doctor_id; 
    var query = {_id:_id}; 

    const customerFindPromise = CustomerCases.findById(_id); 
    const customerRemovePromise = CustomerCases.remove(query); 
    const doctorUpdatePromise = Doctors.findOneAndUpdate({_id:doctor_id},{'$inc': {'numOfCases': -1}},{new:true}); 

    await Promise.all([customerFindPromise,doctorUpdatePromise,customerRemovePromise]) 
     .then((result) => { 
     console.log("******************** START result0: "+ result[0] +" result END ********************"); 
     console.log("******************** START result1: "+ result[1] +" result END ********************"); 
     console.log("******************** START result2: "+ result[2] +" result END ********************"); 
     res.json(result); 
     }).catch((err) => { 
      console.log("******************** START err: "+ err +" err END ********************"); 
     throw err; 
     }); 
} 
+0

게시 된 코드가 유효하지 않습니다. 특히 'var customer'선언이 있습니다. –

+0

동일한 ID를 가진 객체를 찾아서 동시에 제거하는 것은 고전적인 경쟁 조건처럼 보입니다. – Bergi

답변

0

실행중인 기능이 비동기 항상 순서대로 실행되지 않습니다. Promise.all은 약속의 실행 순서를 변경하지 않고 모두 해결되기를 기다립니다.

때때로 CustomerCases.removeCustomerCases.findById보다 먼저 실행되어 해결되므로 null은 문서가 먼저 제거 될 때 해결됩니다. 당신이 추가 상당히 간단 async/await를 사용하는 같은 약속에 대한

기다립니다보고, 다음 쿼리를 실행하기 전에 직렬 해결하려면

try{ 
    let find = await CustomerCases.findById(_id) 
    console.log(`find: ${find}`) 
    let update = await CustomerCases.remove(query) 
    console.log(`update: ${update}`) 
    let remove = await Doctors.findOneAndUpdate({_id:doctor_id},{'$inc': {'numOfCases': -1}},{new:true}) 
    console.log(`remove: ${update}`) 
    res.json([find, update, remove]) 
} catch(err) { 
    console.error(err) 
    throw err // next(err)? 
} 

해보십시오 파랑새 Promise.each를 직렬 실행 도우미가 필요합니다.

+0

약속은 "실행"하지 않으며'Promise.all'에 "실행"이 없으므로 명령도 없습니다. – Bergi

+0

@Bergi 더 나은 용어? – Matt

+0

@Matt, 고맙습니다. 약속을 기다리고 있습니다. 동시에 모든 약속을 이행하지 않을 것입니다. Promise.all을 추가하기 위해 멀리 있고,이 상황에 필요합니다. – publicArt33

관련 문제