0

i have code like below

const somePromises = values.map(({variable, value}) => 
    this.post('/api/values/', {
        variable,
        value,
        item: itemId,
    })
);
await Promise.all(somePromises);

if (somecondition) {
    params.var = var;
    await this.patch('/api/items/${itemId}/', params);
}

the above code works but i want to execute if clause only if there is values has some value or if somePromises is resolved.

so was trying something like below,

const somePromises = values.map(({variable, value}) => 
    this.post('/api/values/', {
        variable,
        value,
        item: itemId,
    })
);
await Promise.all(somePromises).then (() => {
    if (somecondition) {
    params.var = var;
    await this.patch('/api/items/${itemId}/', params); //but throws err here
}
});

but throws error await cant be used here and async should be used. how can i fix this issue. could someone help me with this. thanks.

2 Answers 2

2

Assuming this.patch returns a Promise, you can return it if it passes the conditions, or return a resolved Promise:


Promise.all(somePromises).then(() => {
    if (somecondition) {
      return this.patch('/api/items/${itemId}/', params);
    } else {
      return Promise.resolve(null);
    }
}).then(response => {
  if (response) {
  // do something with response, the returned value from this.patch
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You are using await inside your callback function body. So, that callback function also should by async if you want to await inside it.

await Promise.all(somePromises).then(async () => {
    if (somecondition) {
        params.var = var;
        await this.patch('/api/items/${itemId}/', params);
    }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.