0

I have a variable:

let x = 1;

What is the simplest way to create a Promise that will right away return the x ? Something like:

let promise = Promise(x);

The question is not about when and how to use Promises. It is clear.

Tom Smykowski
  • 25,487
  • 54
  • 159
  • 236

2 Answers2

2

You make a resolved promise like this:

let x = 1;
let promise = Promise.resolve(x);

Also you can make a rejected promise:

let rejectedPromise = Promise.reject(x);
Yoihito
  • 348
  • 2
  • 13
1

I agree with others Promise.resolve is a straightforward way to wrap a value into Promise. One more option is to use sync and async values inside function:

async function foo<T>(value: T): Promise<T> {
  // do something async
  // and/or return simple value
  return value;
}

const a: Promise<number> = foo(123);
const b: number = await foo(123);