-1

I saw that putting async in front of a JS function returns a Promise.

What I have now:

    async function asyncTest(p) {
        return p;
    } 

    let www = asyncTest(1)
    console.log('www ', www); // returns Promise {<fulfilled>: 1}, see image

enter image description here

I was wondering if I could use this to have resolved and rejected in an async, acting like a typical new Promise((resolved, rejected)....

What I would like to do:

    async function asyncTest(p, (resolved, rejected)=>{

      resolved(p);

    }) 

    let www = asyncTest(1)
    console.log('www ', www); // I want it to return 1

Is this even possible?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
codebot
  • 517
  • 8
  • 29
  • 55
  • `async` functions _always_ return promises (as does `new Promise((resolve, reject) => ...)`), you can't somehow re-synchronise it to get the value without either `await` or `.then`. – jonrsharpe Jul 24 '21 at 17:02
  • 1
    I don't understand what you want. First you acknowledge that an `async` function always returns a promise object, but then you want `www` *not* to be a promise object?? – trincot Jul 24 '21 at 17:02
  • If you don't want to return a promise, write an ordinary function that creates a promise and calls `resolve()` itself. – Barmar Jul 24 '21 at 17:04
  • 1
    If you want to generate an *asynchronous* result, then that result will be available in the *future*, and you cannot expect it to be available *now*. – trincot Jul 24 '21 at 17:15

1 Answers1

0

I was wondering if I could use this to have resolved and rejected in an async, acting like a typical new Promise((resolved, rejected)…

No. An async function does not provide you with callbacks to resolve/reject a promise, it only provides you with await. You can re-create Promise.resolve and Promise.reject with

async function resolve(x) { return x; }
async function reject(x) { throw x; }`

but that's it. To promisify a callback API, you always need to use the new Promise constructor.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375