Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/451.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 根据承诺值停止post请求函数的执行?_Javascript_Express_Mongoose - Fatal编程技术网

Javascript 根据承诺值停止post请求函数的执行?

Javascript 根据承诺值停止post请求函数的执行?,javascript,express,mongoose,Javascript,Express,Mongoose,当我在express中处理POST请求时,我需要在mongoDB集群上获取一些数据,根据响应,我必须使用请求进行响应 app.post('/api/persons',(请求、响应)=>{ const body=request.body; 如果(!body.name | |!body.number){ 返回response.status(400.json)({ 错误:“缺少名称或编号”, }); } const newName=body.name; //if(phoneBook.some((per

当我在express中处理POST请求时,我需要在mongoDB集群上获取一些数据,根据响应,我必须使用请求进行响应

app.post('/api/persons',(请求、响应)=>{
const body=request.body;
如果(!body.name | |!body.number){
返回response.status(400.json)({
错误:“缺少名称或编号”,
});
}
const newName=body.name;
//if(phoneBook.some((person)=>person.name==newName)){
//返回response.status(409).send({error:'Name应该是唯一的'});
// }
Person.find({name:newName})。然后((num)=>{
如果(num.length!==0){
返回response.status(409.json)({
错误:“名称必须唯一”,
});
}
});
常数记录=新的人({
name:body.name,
编号:body.number,
});
record.save().then((savedRecord)=>{
json(savedRecord);
});
});
Person是mongoDB模型

Person.find
检查该值并以布尔值响应。我目前面临两个问题

  • .find
    调用中获取值后,函数应该在我用返回值响应时结束,但它仍然继续,并使用下面的
    record.save()
    保存值

  • 即使该值不存在,它仍然显示
    名称必须唯一的错误。
    //通过将
    .exist()
    替换为
    .find()

  • 有没有一种方法可以在不在find promise中添加
    record.save()
    的情况下解决此问题?我希望
    .find
    调用存在于它自己的函数中,我将如何进行此操作


    谢谢

    创建一个单独的
    findFunction
    ,它将调用
    Person。查找
    并将
    newName
    foundCallback
    notFoundCallback
    作为参数。请检查以下代码

    const findFunction = (newName, foundCallback, notFoundCallback) => {
        Person.find({ name: newName }).then((num) => {
            if (num.length !== 0) {
                foundCallback();
            } else {
                notFoundCallback();
            }
        });
    }
    
    app.post('/api/persons', (request, response) => {
        const body = request.body;
    
        if (!body.name || !body.number) {
            return response.status(400).json({
                error: 'Name or Number missing',
            });
        }
    
        const newName = body.name;
    
        findFunction(
            newName,
            () => response.status(409).json({ error: 'Name must be unique' }),
            () => {
                const record = new Person({
                    name: body.name,
                    number: body.number,
                });
    
                record.save().then((savedRecord) => {
                    response.json(savedRecord);
                });
            }
        );
    });
    
    如果您更喜欢基于承诺的解决方案,那么:

    const ensurePersonIsUnique = (newName) => {
        return new Promise((resolve, reject) => {
            Person.find({ name: newName }).then((num) => {
                if (num.length !== 0) {
                    reject();
                } else {
                    resolve();
                }
            });
        });
    }
    
    app.post('/api/persons', (request, response) => {
        const body = request.body;
    
        if (!body.name || !body.number) {
            return response.status(400).json({
                error: 'Name or Number missing',
            });
        }
    
        const newName = body.name;
    
        ensurePersonIsUnique(newName).then(() => {
            const record = new Person({
                name: body.name,
                number: body.number,
            });
    
            record.save().then((savedRecord) => {
                response.json(savedRecord);
            });
        }).catch(() => {
            response.status(409).json({ error: 'Name must be unique' })
        });
    });
    

    仅当
    num.length!==0
    ,这是情况/预期结果吗?@axtck是的,这部分工作正常。但是函数的执行并没有在这里停止,我要做的是停止执行并返回409响应,但它仍然继续执行,直到最后一次返回409响应。是的,我也找到了承诺解决方案。谢谢