简体   繁体   中英

How to make the program wait for the if statement to finish before continuing in javascript?

I'm new to Javascript. I want to make this block run after the if statement is finished (asynchronous). The reason I want that is that I want to make some changes to update them if it falls into the if statement

let params = {
            TableName: "storepedia-test",
            Item: updatedItem
        };
    
        docClient.put(params, function (err, data) {
            if (err) {
                console.log(err);
            } else {
                res.redirect('/devices');
            }
        });

Here is my whole code

const { id } = req.params;
const file = req.file;
let updatedItem = { ...req.body};
updatedItem.id = id;
    if (file !== undefined){
        const deleteParams = {
            Key: updatedItem.image,
            Bucket: bucketName
        }
        s3.deleteObject(deleteParams, async (err, data) => {
            if (err) {
                console.log(err)
            } else {
                const result = await uploadFile(file);
                console.log('result', result);
                await unlinkFile(file.path);
                updatedItem.image = result.Key;
                let params = {
                    TableName: "storepedia-test",
                    Item: updatedItem
                };
            
                docClient.put(params, function (err, data) {
                    if (err) {
                        console.log(err);
                    } else {
                        res.redirect('/devices');
                    }
                });
            }
        })     
    } 

        let params = {
            TableName: "storepedia-test",
            Item: updatedItem
        };
    
        docClient.put(params, function (err, data) {
            if (err) {
                console.log(err);
            } else {
                res.redirect('/devices');
            }
        });
  

Just to run something after the if ? I think this is the best spot:

 docClient.put(params, function(err, data) { if (err) { console.log(err); } else { // run async code here. // when done do the redirect. // for example: s3.do_something(function(err, data) { if (err) { console.log(err) } else { console.log(data) res.redirect('/devices'); } }) } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM