Prepare for the Salesforce JavaScript Developer Exam. Utilize comprehensive quizzes, flashcards, and multiple choice questions with hints and explanations. Boost your exam readiness!

Practice this question and more.


Given two promises, which of the following correctly executes them in sequence?

  1. p1().then(() => p2()).then(result => result);

  2. p1.then((data) => p2(data)).then(result => result);

  3. async function getResult() { const data = await p1; return await p2(data); }

  4. async function getResult() { const data = p1; const result = p2(data); }

The correct answer is: p1.then((data) => p2(data)).then(result => result);

The correct choice is based on how promises work in JavaScript. Each promise represents an operation that will complete in the future, and you can chain them to ensure they execute in a specific order. The correct answer executes the two promises in sequence by using the `then` method with a callback that passes the result of the first promise to the second. In option B, after invoking `p1`, the `then` method is used to handle the resolution of the promise. The result from `p1` is passed as an argument to the function that executes `p2`, ensuring that `p2` only begins executing once `p1` has completed. This guarantees that their execution is sequential: `p1` finishes its operation before `p2` starts, and the return value from `p2` can be handled in subsequent `then` methods. This behavior contrasts with the other options. While A also executes the promises in sequence, it utilizes a function `p1()`, suggesting it's returning a promise from a function call rather than handling an existing promise directly. It's conceptually valid, but only if `p1` is indeed a function returning a promise. Therefore, option A could be correct depending on its context, but